这可能对你有点晚了,但其他人可能会发现这很有用。
首先,你需要创建多个CONTENT_URIs
public static final Uri CONTENT_URI1 =
Uri.parse("content://"+ PROVIDER_NAME + "/sampleuri1");
public static final Uri CONTENT_URI2 =
Uri.parse("content://"+ PROVIDER_NAME + "/sampleuri2");
然后你扩大你的URI匹配器
private static final UriMatcher uriMatcher;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "sampleuri1", SAMPLE1);
uriMatcher.addURI(PROVIDER_NAME, "sampleuri1/#", SAMPLE1_ID);
uriMatcher.addURI(PROVIDER_NAME, "sampleuri2", SAMPLE2);
uriMatcher.addURI(PROVIDER_NAME, "sampleuri2/#", SAMPLE2_ID);
}
然后创建表
private static final String DATABASE_NAME = "sample.db";
private static final String DATABASE_TABLE1 = "sample1";
private static final String DATABASE_TABLE2 = "sample2";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE1 =
"CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE1 +
" (" + _ID1 + " INTEGER PRIMARY KEY AUTOINCREMENT," +
"data text, stuff text);";
private static final String DATABASE_CREATE2 =
"CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE2 +
" (" + _ID2 + " INTEGER PRIMARY KEY AUTOINCREMENT," +
"data text, stuff text);";
不要忘了添加第二个DATABASE_CREATE
至onCreate()
你要使用的switch-case块来确定使用什么表。这是我的插入代码
@Override
public Uri insert(Uri uri, ContentValues values) {
Uri _uri = null;
switch (uriMatcher.match(uri)){
case SAMPLE1:
long _ID1 = db.insert(DATABASE_TABLE1, "", values);
//---if added successfully---
if (_ID1 > 0) {
_uri = ContentUris.withAppendedId(CONTENT_URI1, _ID1);
getContext().getContentResolver().notifyChange(_uri, null);
}
break;
case SAMPLE2:
long _ID2 = db.insert(DATABASE_TABLE2, "", values);
//---if added successfully---
if (_ID2 > 0) {
_uri = ContentUris.withAppendedId(CONTENT_URI2, _ID2);
getContext().getContentResolver().notifyChange(_uri, null);
}
break;
default: throw new SQLException("Failed to insert row into " + uri);
}
return _uri;
}
您需要devide了delete
,update
,getType
等无论您的供应商要求DATABASE_TABLE或CONTENT_URI你会在一个和#2增加的情况下,并有DATABASE_TABLE1或CONTENT_URI1在下一个等等,尽可能多的你想要的。
来源
2010-12-05 18:04:36
Opy
com.android.providers.contacts.ContactsProvider2.java https://github.com/android/platform_packages_providers_contactsprovider/blob/master/src/com/android/providers/contacts/ContactsProvider2.java – Alex 2013-02-27 19:29:43
@ Marloke谢谢。好吧,我明白即使是Android团队使用'switch'解决方案,但是您提到的这个部分:'他们通过提供专业视图来处理跨表查询,然后您在后端运行查询。在前端,通过单个内容提供者可以通过各种不同的URI访问调用者。你认为你可以更详细地解释一下吗? – eddy 2014-12-01 12:50:11