Android中使用Content Providers进行数据共享的实例[页10]
2023-08-23次
javapublic class MyContentProvider extends ContentProvider {
private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
private static final int MY_DATA = 1;
static {
sUriMatcher.addURI("com.example.myapp.provider", "my_data", MY_DATA);
}
private SQLiteDatabase mDatabase;
@Override
public boolean onCreate() {
mDatabase = new MyDatabaseHelper(getContext()).getWritableDatabase();
return true;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
Cursor cursor;
switch (sUriMatcher.match(uri)) {
case MY_DATA:
cursor = mDatabase.query("my_data", projection, selection, selectionArgs, null, null, sortOrder);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
switch (sUriMatcher.match(uri)) {
case MY_DATA:
return "vnd.android.cursor.dir/my_data";
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
long id = mDatabase.insert("my_data", null, values);
getContext().getContentResolver().notifyChange(uri, null);
return ContentUris.withAppendedId(uri, id);
}
@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
int count;
switch (sUriMatcher.match(uri)) {
case MY_DATA:
count = mDatabase.delete("my_data", selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
int count;
switch (sUriMatcher.match(uri)) {
case MY_DATA:
count = mDatabase.update("my_data", values, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
}
上述代码中,首先定义了一个UriMatcher对象,用于匹配URI。在Content Provider的静态代码块中,将需要支持的URI添加到UriMatcher中。例如,"com.example.myapp.provider/my_data"这个URI对应的整数值为1。