一、ContentResolver 的基本用法
1. 內(nèi)容 URI
不同于 SQLiteDatabase,ContentResolver 中的增刪改查方法都是不接收表名參數(shù)的,而是使用一個 Uri 參數(shù)代替,這個參數(shù)被稱為內(nèi)容 URI。
主要由兩部分組成,權(quán)限(authority)和 路徑(path)。
- 權(quán)限(authority):用于對不同的應(yīng)用程序做區(qū)分的,一般為了避免沖突,都會采用程序包名的方式來進(jìn)行命名。如:com.example.app.provider
- 路徑(path):用于對同一應(yīng)用程序中不同的表做區(qū)分的,通常都會添加到權(quán)限的后面。如:/table1
- 還需要在字符串的頭部加上 協(xié)議聲明:content://
- 結(jié)合起來 內(nèi)容 URI 就是:content://com.example.app.provider/table1
2. ContentResolver 使用步驟
(1). 通過 Context 中的 getContentResolver() 方法獲得實例。
(2). 組裝出 內(nèi)容 URI。
(3). 把內(nèi)容 URI 解析成 Uri 對象:
Uri uri = Uri.parse("content://com.example.app.provider/table1")
(4). 增刪改查。
二、增刪改查
1. 查詢數(shù)據(jù)
Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);

if (cursor != null) {
while (cursor.moveToNext()) {
String column1 = cursor.getString(cursor.getColumnIndex("column1"));
int column2 = cursor.getInt(cursor.getColumnIndex("column2"));
}
cursor.close();
}
2. 添加數(shù)據(jù)
ContentValues values = new ContentValues();
values.put("column1", "text");
values.put("column2", 1);
getContentResolver().insert(uri, values);
3. 更新數(shù)據(jù)
ContentValues values = new ContentValues();
values.put("column1", "");
getContentResolver().update(uri, values, "column1 = ? and column2 = ?", new String[] {"text", "1"});
4. 刪除數(shù)據(jù)
getContentResolver().delete(uri, "column2 = ?", new String[] { "1" });