使用一个ContentProvider操作多张表
在我们开发过程中,通常使用ContentProvider来操作数据。查询数据库中的一张表的数据我们创建一个ContentProvider提供操作,需要访问多张表中的数据时,可以创建多个对应的ContentProvider来操作数据。
当然,如果只用一个ContentProvider来操作同一个数据库中的多张表也是可以实现的。ContentProvider所提供的CRUD方法都是通过uri来实现,使用一个ContentProvider操作多张表,也就是说一个authority,然后多个CONTENT_URI对应多张表。思路大概就是这样子,下面给出代码,代码是在NotePad源码上做了修改:
NotePad类(契约类)中声明AUTHORITY,class Notes对应数据库中的Notes表,class NotesGroup对应 NotesGroup表,它们有各自的CONTENT_URI。
NotePad.java
public final class NotePad {
public static final String AUTHORITY = "com.google.provider.NotePad";
// This class cannot be instantiated
private NotePad() {
}
/**
* Notes table contract
*/
public static final class Notes implements BaseColumns {
// This class cannot be instantiated
private Notes() {}
/**
* The table name offered by this provider
*/
public static final String TABLE_NAME = "notes";
/*
* URI definitions
*/
/**
* The scheme part for this provider's URI
*/
private static final String SCHEME = "content://";
/**
* Path parts for the URIs
*/
/**
* Path part for the Notes URI
*/
private static final String PATH_NOTES = "/notes";
/**
* Path part for the Note ID URI
*/
private static final String PATH_NOTE_ID = "/notes/";
/**
* 0-relative position of a note ID segment in the path part of a note ID URI
*/
public static final int NOTE_ID_PATH_POSITION = 1;
/**
* Path part for the Live Folder URI
*/
private static final String PATH_LIVE_FOLDER = "/live_folders/notes";
/**
* The content:// style URL for this table
*/
public static final Uri CONTENT_URI = Uri.parse(SCHEME + AUTHORITY + PATH_NOTES);
/**
* The content URI base for a single note. Callers must
* append a numeric note id to this Uri to retrieve a note
*/
public static final Uri CONTENT_ID_URI_BASE
= Uri.parse(SCHEME + AUTHORITY + PATH_NOTE_ID);
/**
* The content URI match pattern for a single note, specified by its ID. Use this to match
* incoming URIs or to construct an Intent.
*/
public static final Uri CONTENT_ID_URI_PATTERN
= Uri.parse(SCHEME + AUTHORITY + PATH_NOTE_ID + "/#");
/**
* The content Uri pattern for a notes listing for live folders
*/
public static final Uri LIVE_FOLDER_URI
= Uri.parse(SCHEME + AUTHORITY + PATH_LIVE_FOLDER);
/*
* MIME type definitions
*/
/**
* The MIME type of {@link #CONTENT_URI} providing a directory of notes.
*/
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.note";
/**
* The MIME type of a {@link #CONTENT_URI} sub-directory of a single
* note.
*/
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.google.note";
/**
* The default sort order for this table
*/
public sta