ContentProvider 大概是 Android 四大元件裡最容易被低估的一個。它看起來只是包一層 CRUD,但一旦理解「它把資料庫藏在自己應用程式背後,只對外開一個 Uri 門窗」這件事,很多原本想不通的設計就順了。本文用一個生詞本當例子,把整套流程走完一次。
Android 的應用程式彼此沙箱隔離,A 想讀 B 的資料,不能直連對方的 SQLite 檔。ContentProvider 的做法是:資料庫留在自己家,對外只暴露一個 content:// 開頭的 Uri,外部呼叫端一律透過 ContentResolver 發請求,由 Provider 決定要給什麼、給多少。通訊協定因此被統一成 insert、delete、update、query 四個動作,加上 getType 描述資料型別。
Authority 是這個 Provider 在系統裡的身分證,必須全域唯一,慣例用反向網域。Uri 則是資源的位址,通常一個給「集合」,一個給「單筆」。
public final class Words {
public static final String AUTHORITY = "org.crazyit.providers.dictprovider";
public static final class Word implements BaseColumns {
public final static String _ID = "_id";
public final static String WORD = "word";
public final static String DETAIL = "detail";
public final static Uri DICT_CONTENT_URI =
Uri.parse("content://" + AUTHORITY + "/words");
public final static Uri WORD_CONTENT_URI =
Uri.parse("content://" + AUTHORITY + "/word");
}
}
注意 _id 這個欄位名稱不是約定俗成而已,Cursor 與 SimpleAdapter 之類的元件都預期它存在。
public class MyDatabaseHelper extends SQLiteOpenHelper {
final String CREATE_TABLE_SQL =
"create table dict(_id integer primary key autoincrement, word, detail)";
public MyDatabaseHelper(Context context, String name, int version) {
super(context, name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_SQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
}
Provider 的每個方法開頭幾乎都是同一句 matcher.match(uri)。註冊時把兩種 Uri 映射到兩個整數常數,後續就用 switch 分流:給的是集合就整批處理,給的是帶 ID 的單筆就先 ContentUris.parseId(uri) 取出主鍵,再把它 AND 進 where 條件。
private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
private static final int WORDS = 1;
private static final int WORD = 2;
static {
matcher.addURI(Words.AUTHORITY, "words", WORDS);
matcher.addURI(Words.AUTHORITY, "word/#", WORD);
}
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
long rowId = db.insert("dict", Words.Word._ID, values);
if (rowId > 0) {
Uri wordUri = ContentUris.withAppendedId(uri, rowId);
getContext().getContentResolver().notifyChange(wordUri, null);
return wordUri;
}
return null;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
switch (matcher.match(uri)) {
case WORDS:
return db.query("dict", projection, selection, selectionArgs, null, null, sortOrder);
case WORD:
long id = ContentUris.parseId(uri);
String where = Words.Word._ID + "=" + id;
if (selection != null && !"".equals(selection)) {
where = where + " and " + selection;
}
return db.query("dict", projection, where, selectionArgs, null, null, sortOrder);
default:
throw new IllegalArgumentException("未知 Uri:" + uri);
}
}
delete 與 update 的骨架與 query 幾乎一模一樣,只是回傳受影響的列數。四個方法共同的收尾動作是呼叫 notifyChange,向所有觀察這個 Uri 的人廣播「資料變了」,這是 ContentObserver 能自動刷新的關鍵。
getType 則回報 MIME 型別,多筆用 vnd.android.cursor.dir/ 前綴,單筆用 vnd.android.cursor.item/,後面接自己的 authority 風格字串。
<provider android:name=".DictProvider"
android:authorities="org.crazyit.providers.dictprovider" />
authorities 必須和程式碼裡的 AUTHORITY 完全一致,這是最常見的低級錯誤來源。若結果頁要用 Dialog 樣式彈出,也在同一份 Manifest 中為該 Activity 指定 Theme.Dialog。
主畫面放插入與查詢兩顆按鈕。插入就是把輸入值塞進 ContentValues,再交給 resolver;查詢則是丟一個 LIKE 條件,把結果轉成 List<Map> 帶到下一頁。
ContentValues values = new ContentValues();
values.put(Words.Word.WORD, word);
values.put(Words.Word.DETAIL, detail);
contentResolver.insert(Words.Word.DICT_CONTENT_URI, values);
Cursor cursor = contentResolver.query(
Words.Word.DICT_CONTENT_URI, null,
"word like ? or detail like ?",
new String[]{"%" + key + "%", "%" + key + "%"}, null);
結果頁用 SimpleAdapter 把 List 潑到 ListView 上,欄位名稱對應配置檔中的 TextView id 即可:
SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.line,
new String[]{"word", "detail"},
new int[]{R.id.word, R.id.detail});
listView.setAdapter(adapter);
ContentProvider 上手門檻高,多半卡在兩件事:一是 Uri 與 Authority 的字串對不起來,二是忘記 notifyChange 導致觀察者不更新。把「Uri 決定操作哪筆資料、UriMatcher 負責分流、notifyChange 負責通知」這三條記牢,剩下的 CRUD 就是普通 SQLite 操作的包裝。它真正的價值在於當你日後需要讓其他 App(例如搜尋、分享、小工具)讀到你的資料時,介面已經準備好了。