訪問其他程序中的數(shù)據(jù)

一、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" });
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容