contentprovider读写代码
时间: 2023-05-22 21:02:12 浏览: 72
以下是一个简单的 ContentProvider 读写代码示例:
```
public class MyContentProvider extends ContentProvider {
private static final String AUTHORITY = "com.example.mycontentprovider";
private static final String TABLE_NAME = "mytable";
private static final int URI_CODE = 1;
private static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
static {
URI_MATCHER.addURI(AUTHORITY, TABLE_NAME, URI_CODE);
}
private SQLiteDatabase database;
@Override
public boolean onCreate() {
database = 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 = null;
switch (URI_MATCHER.match(uri)) {
case URI_CODE:
cursor = database.query(TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
return cursor;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
Uri resultUri = null;
switch (URI_MATCHER.match(uri)) {
case URI_CODE:
long id = database.insert(TABLE_NAME, null, values);
resultUri = ContentUris.withAppendedId(uri, id);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
return resultUri;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
int count = 0;
switch (URI_MATCHER.match(uri)) {
case URI_CODE:
count = database.delete(TABLE_NAME, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
return count;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
int count = 0;
switch (URI_MATCHER.match(uri)) {
case URI_CODE:
count = database.update(TABLE_NAME, values, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
return count;
}
}
```
这是一个简单的 ContentProvider 实现,它可以对一个名为 "mytable" 的表进行读写操作。在 onCreate() 方法中,我们获取了一个可写的 SQLiteDatabase 对象,这个对象可以用于执行 SQL 语句。在 query()、insert()、delete()、update() 方法中,我们根据传入的 Uri 参数来判断要操作的表以及要执行的操作类型,然后调用 SQLiteDatabase 对象的相应方法来执行操作。