ContentResolver和ContentProvider是Android中用于实现数据共享和访问的重要组件。
public class MyContentProvider extends ContentProvider {
private DBHelper dbHelper; // 数据库帮助类
@Override
public boolean onCreate() {
dbHelper = new DBHelper(getContext());
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query("table_name", projection, selection, selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
long id = db.insert("table_name", null, values);
getContext().getContentResolver().notifyChange(uri, null);
return ContentUris.withAppendedId(uri, id);
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
int rows = db.update("table_name", values, selection, selectionArgs);
getContext().getContentResolver().notifyChange(uri, null);
return rows;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
int rows = db.delete("table_name", selection, selectionArgs);
getContext().getContentResolver().notifyChange(uri, null);
return rows;
}
@Override
public String getType(Uri uri) {
return null;
}
}
在使用ContentResolver和ContentProvider时,需要先注册ContentProvider并在AndroidManifest.xml中声明权限和uri。然后可以通过ContentResolver来操作数据,例如查询、插入、更新、删除等操作。
以上是ContentResolver和ContentProvider的基本使用方法,开发者可以根据具体的需求来进一步深入学习和使用。