现在,如果我想查询另一个表,比如说 nodo,我将如何更改 ContentProvider?
查询新表意味着您需要添加一个新表Uri
,因为它Uri
选择数据源,类似于使用不同的表。
您将基本上为其他表的待办事项添加所有已经存在的硬编码值。例如:
// ------- usually the same for all
private static final String AUTHORITY = "de.vogella.android.todos.contentprovider";
// ------- define some Uris
private static final String PATH_TODOS = "todos";
private static final String PATH_REMINDERS = "reminders";
public static final Uri CONTENT_URI_TODOS = Uri.parse("content://" + AUTHORITY
+ "/" + PATH_TODOS);
public static final Uri CONTENT_URI_REMINDERS = Uri.parse("content://" + AUTHORITY
+ "/" + PATH_REMINDERS);
// ------- maybe also define CONTENT_TYPE for each
// ------- setup UriMatcher
private static final int TODOS = 10;
private static final int TODO_ID = 20;
private static final int REMINDERS = 30;
private static final int REMINDERS_ID = 40;
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
sURIMatcher.addURI(AUTHORITY, PATH_TODOS, TODOS);
sURIMatcher.addURI(AUTHORITY, PATH_TODOS + "/#", TODO_ID);
sURIMatcher.addURI(AUTHORITY, PATH_REMINDERS, REMINDERS);
sURIMatcher.addURI(AUTHORITY, PATH_REMINDERS + "/#", REMINDERS_ID);
}
//@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// Using SQLiteQueryBuilder instead of query() method
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
int uriType = sURIMatcher.match(uri);
switch (uriType) {
case TODO_ID:
// Adding the ID to the original query
queryBuilder.appendWhere(TodoTable.COLUMN_ID + "="
+ uri.getLastPathSegment());
//$FALL-THROUGH$
case TODOS:
queryBuilder.setTables(TodoTable.TABLE_TODO);
break;
case REMINDERS_ID:
// Adding the ID to the original query
queryBuilder.appendWhere(ReminderTable.COLUMN_ID + "="
+ uri.getLastPathSegment());
//$FALL-THROUGH$
case REMINDERS:
queryBuilder.setTables(ReminderTable.TABLE_REMINDER);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
我应该以某种方式在 queryBuilder.setTables(String inTables) 中附加表名吗?
是的,如果Uri
从不同的表中读取不同的 s,则根据 Uri 匹配设置表。
CONTENT_TYPE 和 CONTENT_ITEM_TYPE 怎么样,每个表都应该有一个吗?
取决于实际的内容类型。如果它们不同并且您需要类型是。但你根本不需要拥有它们。该示例定义了它们,但甚至没有使用它们。它需要返回类型getType
,请参阅文档。
关于 TODO 和 TODO_ID 变量以及查询方法中的开关?
这些是为 定义的常量,这里UriMatcher
很好地解释了。它基本上是字符串匹配的简化。一个大的可以有 100 个不同的 Uris,如果你不得不一直写,那么选择正确的表会很痛苦。ContentProvider
query
if (uri.getPath().equals("todos") { /* code */ } else if (uri..