我有一个SQLite数据库的Content Provider,它有多个表并使用如下所示的URI:
Uri.parse("content://" + AUTHORITY + "/" + TABLE_NAME);
这似乎是标准模式,1个URI到1个数据库表,所有行都有1个CONTENT_TYPE,单行有1个。
但是,我需要为表数据的子集提供URI。我目前在我的数据库中添加大量额外的表是没有意义的。看起来好像内容提供商是为处理这个而设计的,我只是看不到它。基本上我想要一个指向查询而不是表的URI。希望这是有道理的。
答案 0 :(得分:4)
您只需添加应用程序所需的新URI,然后修改内容提供商的查询方法:
public class ExampleProvider extends ContentProvider {
private static final UriMatcher sUriMatcher;
sUriMatcher.addURI("com.example.app.provider", "table3", 1);
sUriMatcher.addURI("com.example.app.provider", "table3/#", 2);
sUriMatcher.addURI("com.example.app.provider", "table3/customquery", 3);
public Cursor query(
Uri uri,
String[] projection,
String selection,
String[] selectionArgs,
String sortOrder) {
switch (sUriMatcher.match(uri)) {
// If the incoming URI was for all of table3
case 1:
if (TextUtils.isEmpty(sortOrder)) sortOrder = "_ID ASC";
break;
// If the incoming URI was for a single row
case 2:
/*
* Because this URI was for a single row, the _ID value part is
* present. Get the last path segment from the URI; this is the _ID value.
* Then, append the value to the WHERE clause for the query
*/
selection = selection + "_ID = " uri.getLastPathSegment();
break;
case 3:
// handle your custom query here
break;
}
// call the code to actually do the query
}