在Android中,通過ContentResolver可以實現對數據的增刪改查操作
要使用ContentResolver插入數據,需要創建一個ContentValues對象來存儲要插入的數據。然后,調用ContentResolver的insert()方法將數據插入到指定的URI。
ContentValues values = new ContentValues();
values.put("column_name1", "value1");
values.put("column_name2", "value2");
// ... 添加其他列的值
ContentResolver contentResolver = getContentResolver();
Uri uri = Uri.parse("content://your_authority/your_path");
Uri insertedUri = contentResolver.insert(uri, values);
要使用ContentResolver刪除數據,需要指定要刪除的數據所在的URI和篩選條件。調用delete()方法后,將返回被刪除的行數。
ContentResolver contentResolver = getContentResolver();
Uri uri = Uri.parse("content://your_authority/your_path");
String selection = "column_name = ?";
String[] selectionArgs = new String[]{"value"};
int deletedRows = contentResolver.delete(uri, selection, selectionArgs);
要使用ContentResolver更新數據,需要創建一個ContentValues對象來存儲要更新的數據。然后,指定要更新的數據所在的URI和篩選條件。調用update()方法后,將返回被更新的行數。
ContentValues values = new ContentValues();
values.put("column_name1", "new_value1");
values.put("column_name2", "new_value2");
// ... 添加其他列的值
ContentResolver contentResolver = getContentResolver();
Uri uri = Uri.parse("content://your_authority/your_path");
String selection = "column_name = ?";
String[] selectionArgs = new String[]{"value"};
int updatedRows = contentResolver.update(uri, values, selection, selectionArgs);
要使用ContentResolver查詢數據,需要指定要查詢的數據所在的URI、要查詢的列名、篩選條件等。調用query()方法后,將返回一個Cursor對象,可以遍歷查詢結果。
ContentResolver contentResolver = getContentResolver();
Uri uri = Uri.parse("content://your_authority/your_path");
String[] projection = new String[]{"column_name1", "column_name2"};
String selection = "column_name = ?";
String[] selectionArgs = new String[]{"value"};
String sortOrder = "column_name1 ASC";
Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, sortOrder);
if (cursor != null) {
while (cursor.moveToNext()) {
String columnValue1 = cursor.getString(cursor.getColumnIndex("column_name1"));
String columnValue2 = cursor.getString(cursor.getColumnIndex("column_name2"));
// ... 處理查詢結果
}
cursor.close();
}
注意:在實際開發中,需要根據自己的ContentProvider實現來設置正確的URI、列名和篩選條件。