編輯:關於 Android 開發
ContentProvider 是 Android 四大元件之一,也是跨應用程式共享資料的唯一標準通道。上一篇談完了概念,這次直接把它寫出來,並用另一個 App 來驗證。
每個 ContentProvider 以 URI 作為唯一識別,格式為 content://authority/path。其他應用只要拿對 URI,就能取得並操作其中的資料。
本專案把不同操作編碼進 path:
content://com.wuyudong.db.personprovider/insert — 新增
content://com.wuyudong.db.personprovider/delete — 刪除
content://com.wuyudong.db.personprovider/update — 更新
content://com.wuyudong.db.personprovider/query — 查詢
這種設計在教學上很直白,但實務上並不建議。Android 的慣例是:用 HTTP 動詞對應 CRUD 的做法不適用於 ContentProvider—— insert 就是 insert()、查詢就是 query(),path 應該表示「資源」而非「動作」。例如 content://com.wuyudong.db.personprovider/person 表示整張表,.../person/5 表示 id 為 5 的那筆。下面先照原設計實作,結尾再說明如何調整成慣例。
UriMatcher 是一個 URI 比對器。它做字面前綴比對,比對成功回傳你註冊時指定的整數,失敗則回傳 UriMatcher.NO_MATCH(-1)。用它可以在 query()、insert() 等方法開頭快速分派邏輯。
package com.wuyudong.db;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
public class PersonDBProvider extends ContentProvider {
// URI 匹配器,路徑不滿足條件時返回 -1
private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
private static final int INSERT = 1;
private static final int DELETE = 2;
private static final int UPDATE = 3;
private static final int QUERY = 4;
private PersonSQLiteOpenHelper helper;
static {
matcher.addURI("com.wuyudong.db.personprovider", "insert", INSERT);
matcher.addURI("com.wuyudong.db.personprovider", "delete", DELETE);
matcher.addURI("com.wuyudong.db.personprovider", "update", UPDATE);
matcher.addURI("com.wuyudong.db.personprovider", "query", QUERY);
}
@Override
public boolean onCreate() {
helper = new PersonSQLiteOpenHelper(getContext());
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
if (matcher.match(uri) == QUERY) {
SQLiteDatabase db = helper.getReadableDatabase();
return db.query("person", projection, selection,
selectionArgs, null, null, sortOrder);
} else {
throw new IllegalArgumentException("路徑不匹配,不能執行查詢操作");
}
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
if (matcher.match(uri) == INSERT) {
SQLiteDatabase db = helper.getWritableDatabase();
db.insert("person", null, values);
} else {
throw new IllegalArgumentException("路徑不匹配,不能執行插入操作");
}
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
if (matcher.match(uri) == DELETE) {
SQLiteDatabase db = helper.getWritableDatabase();
db.delete("person", selection, selectionArgs);
} else {
throw new IllegalArgumentException("路徑不匹配,不能執行刪除操作");
}
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
if (matcher.match(uri) == UPDATE) {
SQLiteDatabase db = helper.getWritableDatabase();
db.update("person", values, selection, selectionArgs);
} else {
throw new IllegalArgumentException("路徑不匹配,不能執行修改操作");
}
return 0;
}
}
寫好類別還不夠,必須在 AndroidManifest.xml 的 <application> 節點內宣告,authority 要與程式碼中的字串完全一致:
<provider
android:name=".PersonDBProvider"
android:authorities="com.wuyudong.db.personprovider"
android:exported="true" />
android:exported="true" 表示允許其他應用存取,這是跨 App 分享的前提。反過來說,如果你並不希望對外開放,就應該設為 false——這是一個常見的資安疏漏點,設成 true 卻沒有搭配權限保護,等於把資料庫大門敞開。
新建一個名為 other 的專案,版面配置放四顆按鈕:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button android:onClick="click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="讀取DB的數據" />
<Button android:onClick="delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="刪除DB的數據" />
<Button android:onClick="update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="修改DB的數據" />
<Button android:onClick="insert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="添加DB的數據" />
</LinearLayout>
呼叫端就只是普通的 ContentResolver 操作:
ContentResolver resolver = getContentResolver();
Uri uri = Uri.parse("content://com.wuyudong.db.personprovider/query");
Cursor cursor = resolver.query(uri, null, null, null, null);
// ... 遍歷 cursor
1. onCreate() 應回傳 true。回傳值代表初始化是否成功,回 false 會讓系統認為 Provider 建立失敗。
2. insert() 要回傳新資料的 Uri,delete()/update() 要回傳受影響的列數。呼叫端可能依賴這些回傳值。目前的範例一律回 null 或 0,是個明顯的缺陷:
long rowId = db.insert("person", null, values);
return Uri.parse("content://com.wuyudong.db.personprovider/person/" + rowId);
3. getType() 不能留空。它應該回傳該 URI 對應的 MIME 型別,例如 vnd.android.cursor.dir/vnd.wuyudong.person(多筆)或 vnd.android.cursor.item/vnd.wuyudong.person(單筆)。有些框架(如 CursorAdapter、LoaderManager)會依賴它。
4. 資料庫連線不要每次操作都開新的。範例中每次呼叫都 getWritableDatabase(),虽然 SQLiteOpenHelper 內部有快取,但仍建議養成使用後關閉或重用同一個 helper 實例的習慣。
5. 改用慣例設計。把四個 path 收斂成一個資源路徑,並用 URI 尾段判斷是否為單筆:
static {
// 全部 person
matcher.addURI(AUTHORITY, "person", PERSON_DIR);
// 單筆 person,# 代表任意數字
matcher.addURI(AUTHORITY, "person/#", PERSON_ITEM);
}
這樣 query() 只需依 PERSON_DIR 或 PERSON_ITEM 兩種情況處理,語意清楚,也符合 Android 官方文件的設計慣例。
Android 網路圖片查看器實作:HttpURLConnection 搭配 Handler 異步載入
Android 網路圖片查看器實作:HttpURLConnection 搭配 Handler 異步載入 這篇記錄如何寫一個簡單的網路圖片查看器:使用者在輸入框貼上圖片網址
Android 進階系列(四):Activity 生命週期與 Intent 的顯式、隱式用法
Android 的三大基礎元件——Activity、Service 與 BroadcastReceiver——都必須靠 Intent 才能啟動。前面幾篇我們已經反覆用到
Android 內存洩漏的幾種典型場景總結
Java 是帶垃圾回收的語言,它的優勢在於開發者無需手動管理內存分配,既降低了因內存錯誤導致進程崩潰的風險,也避免了未釋放的內存把堆空間撐爆。但這並不意味著內存問題從此消
Android 菜單實作指南:選項、子菜單、上下文菜單與 XML 定義
Android 菜單的三種常見形式 Android 菜單主要可分成選項菜單、子菜單與上下文菜單。選項菜單通常由使用者點擊選單鍵或工具列觸發;上下文菜單則常綁定在特定 Vi