Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android ContentProvider 元件詳解:資料模型、URI 與 CRUD 完整實作

編輯:關於 Android 程式設計

ContentProvider 是 Android 四大元件之一,也是跨應用程式共享資料的唯一標準途徑。它的核心職責是儲存與擷取資料,並向其他應用程式提供存取介面。系統本身已為常見資料型別(音樂、影片、圖片、聯絡人資訊等)內建了一系列 Provider,位於 android.provider 套件下,持有適當權限即可存取。

兩種共享自己資料的方式

  1. 建立自己的 ContentProvider:繼承 ContentProvider 並實作必要方法。
  2. 把資料加入既有的 Provider:前提是自己的資料型別與該 Provider 相容,且具備寫入權限。

兩個最重要的概念

資料模型(Data Model)

ContentProvider 以資料表的形式對外呈現資料:每一列是一筆紀錄,每一欄是具有特定型別與意義的資料。每筆紀錄都包含一個 _ID 欄位,用於唯一標識該筆資料——這是 Android 的慣例,CursorAdapter 等元件都依賴它。

URI

每個 ContentProvider 都對外提供一個能唯一標識其資料集的公開 URI。若一個 Provider 管理多個資料集,每個資料集會有各自獨立的 URI。所有 URI 都以 content:// 開頭,其中 content: 這個 scheme 就是用來標示「資料由 ContentProvider 管理」。

由於幾乎所有操作都要用到 URI,實務上應把 URI 定義為常數,既簡化開發也提高可維護性。

如何存取 Provider 中的資料

存取是透過 ContentResolver 物件進行,它提供了查詢、插入、修改、刪除的方法。以查詢為例,你需要掌握三項資訊:

  • 唯一標識該 ContentProvider 的 URI
  • 需要存取的資料欄位名稱
  • 該欄位的資料型別

若要存取特定某一筆紀錄,只要知道該筆的 ID 即可。

query() 與 managedQuery() 的差別

查詢有兩個入口:ContentResolver.query() 與 Activity.managedQuery(),參數完全相同,回傳的都是 Cursor。差別在生命週期管理:managedQuery() 建立的 Cursor 會由 Activity 代管——Activity 進入暫停狀態時自動呼叫 deactivate() 卸載,回到執行狀態時呼叫 requery() 重新查詢。若想把未經管理的 Cursor 交給 Activity 代管,可呼叫 startManagingCursor()。

完整實作範例

以下是一個「員工通訊錄」的完整 CRUD 實作,包含常量定義、Provider、資料庫 Helper 與呼叫端。

1. 常量類別:Employees.java

把 authority、URI、欄位名稱集中管理,是 ContentProvider 開發的基本功。

package com.amaker.ch10.app;

import android.net.Uri;
import android.provider.BaseColumns;

public final class Employees {

    // 授權字串,必須與 Manifest 中的 authorities 一致
    public static final String AUTHORITY = "com.amaker.provider.Employees";

    private Employees() {}

    public static final class Employee implements BaseColumns {

        private Employee() {}

        // 存取 URI
        public static final Uri CONTENT_URI =
                Uri.parse("content://" + AUTHORITY + "/employee");

        // 內容型別:dir 代表多筆,item 代表單筆
        public static final String CONTENT_TYPE =
                "vnd.android.cursor.dir/vnd.amaker.employees";
        public static final String CONTENT_ITEM_TYPE =
                "vnd.android.cursor.item/vnd.amaker.employees";

        public static final String DEFAULT_SORT_ORDER = "name DESC";

        // 資料表欄位
        public static final String NAME = "name";
        public static final String GENDER = "gender";
        public static final String AGE = "age";
    }
}

實作 BaseColumns 即可免費取得 _ID 與 _COUNT 兩個標準欄位常數。

2. 資料庫 Helper:DBHelper.java

public class DBHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "Employees.db";
    private static final int DATABASE_VERSION = 1;
    public static final String EMPLOYEES_TABLE_NAME = "employee";

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + EMPLOYEES_TABLE_NAME + " ("
                + Employee._ID + " INTEGER PRIMARY KEY,"
                + Employee.NAME + " TEXT,"
                + Employee.GENDER + " TEXT,"
                + Employee.AGE + " INTEGER"
                + ");");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS employee");
        onCreate(db);
    }
}

3. Provider 本體:EmployeeProvider.java

Provider 的核心是 UriMatcher——它負責判斷傳入的 URI 是「整個資料集」還是「某一筆特定資料」,據以決定查詢條件。

public class EmployeeProvider extends ContentProvider {

    private DBHelper dbHelper;
    private static final UriMatcher sUriMatcher;

    private static final int EMPLOYEE = 1;      // 全部資料
    private static final int EMPLOYEE_ID = 2;   // 單筆資料

    private static HashMap<String, String> empProjectionMap;

    static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(Employees.AUTHORITY, "employee", EMPLOYEE);
        sUriMatcher.addURI(Employees.AUTHORITY, "employee/#", EMPLOYEE_ID);

        empProjectionMap = new HashMap<String, String>();
        empProjectionMap.put(Employee._ID, Employee._ID);
        empProjectionMap.put(Employee.NAME, Employee.NAME);
        empProjectionMap.put(Employee.GENDER, Employee.GENDER);
        empProjectionMap.put(Employee.AGE, Employee.AGE);
    }

    @Override
    public boolean onCreate() {
        dbHelper = new DBHelper(getContext());
        return true;
    }
}

注意 employee/# 中的 # 是數字萬用字元,用來比對帶 ID 的 URI。

4. 新增與刪除

@Override
public Uri insert(Uri uri, ContentValues values) {
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    long rowId = db.insert(DBHelper.EMPLOYEES_TABLE_NAME, Employee.NAME, values);
    if (rowId > 0) {
        Uri empUri = ContentUris.withAppendedId(Employee.CONTENT_URI, rowId);
        // 通知監聽者資料已變更
        getContext().getContentResolver().notifyChange(empUri, null);
        return empUri;
    }
    return null;
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    int count;
    switch (sUriMatcher.match(uri)) {
        case EMPLOYEE:
            count = db.delete(DBHelper.EMPLOYEES_TABLE_NAME, selection, selectionArgs);
            break;
        case EMPLOYEE_ID:
            String noteId = uri.getPathSegments().get(1);
            count = db.delete(DBHelper.EMPLOYEES_TABLE_NAME,
                    Employee._ID + "=" + noteId
                    + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""),
                    selectionArgs);
            break;
        default:
            throw new IllegalArgumentException("錯誤的 URI " + uri);
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return count;
}

notifyChange() 是 ContentProvider 有別於一般資料庫操作的關鍵:它讓所有註冊了 ContentObserver 的用戶端能即時收到通知並刷新畫面。

5. 查詢與更新

查詢使用 SQLiteQueryBuilder,並在回傳 Cursor 前呼叫 setNotificationUri() 註冊觀察:

@Override
public Cursor query(Uri uri, String[] projection, String selection,
                    String[] selectionArgs, String sortOrder) {
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    switch (sUriMatcher.match(uri)) {
        case EMPLOYEE:
            qb.setTables(DBHelper.EMPLOYEES_TABLE_NAME);
            qb.setProjectionMap(empProjectionMap);
            break;
        case EMPLOYEE_ID:
            qb.setTables(DBHelper.EMPLOYEES_TABLE_NAME);
            qb.setProjectionMap(empProjectionMap);
            qb.appendWhere(Employee._ID + "=" + uri.getPathSegments().get(1));
            break;
        default:
            throw new IllegalArgumentException("Uri錯誤! " + uri);
    }

    String orderBy;
    if (TextUtils.isEmpty(sortOrder)) {
        orderBy = Employee.DEFAULT_SORT_ORDER;
    } else {
        orderBy = sortOrder;
    }

    SQLiteDatabase db = dbHelper.getReadableDatabase();
    Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);
    c.setNotificationUri(getContext().getContentResolver(), uri);
    return c;
}

@Override
public int update(Uri uri, ContentValues values, String selection,
                  String[] selectionArgs) {
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    int count;
    switch (sUriMatcher.match(uri)) {
        case EMPLOYEE:
            count = db.update(DBHelper.EMPLOYEES_TABLE_NAME, values, selection, selectionArgs);
            break;
        case EMPLOYEE_ID:
            String noteId = uri.getPathSegments().get(1);
            count = db.update(DBHelper.EMPLOYEES_TABLE_NAME, values,
                    Employee._ID + "=" + noteId
                    + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""),
                    selectionArgs);
            break;
        default:
            throw new IllegalArgumentException("錯誤的 URI " + uri);
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return count;
}

6. 呼叫端:MainActivity.java

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        insert();
        query();
        update();
        query();
        del();
        query();
    }

    private void insert() {
        Uri uri = Employee.CONTENT_URI;
        ContentValues values = new ContentValues();
        values.put(Employee.NAME, "amaker");
        values.put(Employee.GENDER, "male");
        values.put(Employee.AGE, 30);
        getContentResolver().insert(uri, values);
    }

    private void query() {
        String[] PROJECTION = new String[] {
                Employee._ID,     // 0
                Employee.NAME,    // 1
                Employee.GENDER,  // 2
                Employee.AGE      // 3
        };
        Cursor c = managedQuery(Employee.CONTENT_URI, PROJECTION, null,
                null, Employee.DEFAULT_SORT_ORDER);
        if (c.moveToFirst()) {
            for (int i = 0; i < c.getCount(); i++) {
                c.moveToPosition(i);
                String name = c.getString(1);
                String gender = c.getString(2);
                int age = c.getInt(3);
                Log.i("emp", name + ":" + gender + ":" + age);
            }
        }
    }

    private void update() {
        Uri uri = ContentUris.withAppendedId(Employee.CONTENT_URI, 1);
        ContentValues values = new ContentValues();
        values.put(Employee.NAME, "hz.guo");
        values.put(Employee.GENDER, "male");
        values.put(Employee.AGE, 31);
        getContentResolver().update(uri, values, null, null);
    }

    private void del() {
        Uri uri = ContentUris.withAppendedId(Employee.CONTENT_URI, 1);
        getContentResolver().delete(uri, null, null);
    }
}

ContentUris.withAppendedId() 是組出「帶 ID 的 URI」的標準做法,它會產生 content://.../employee/1 這樣的形式,正好能被 Provider 中的 UriMatcher 比對為 EMPLOYEE_ID。

7. Manifest 註冊

<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.amaker.ch10.app"
    android:versionCode="1"
    android:versionName="1.0">

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <provider android:name="EmployeeProvider"
            android:authorities="com.amaker.provider.Employees" />

        <activity android:name=".MainActivity" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

    <uses-sdk android:minSdkVersion="3" />
</manifest>

android:authorities 必須與 Employees 類別中定義的 AUTHORITY 完全一致,否則 URI 無法解析。

實作要點回顧

  • URI 設計:authority 用套件名的反向形式避免衝突,路徑用複數名詞表示資料集。
  • UriMatcher:區分「全部」與「單筆」兩種情境,是所有 CRUD 方法的入口判斷。
  • notifyChange / setNotificationUri:兩者搭配才能讓資料變更自動反映到所有觀察中的畫面,這是 ContentProvider 的核心價值。
  • _ID 欄位:繼承 BaseColumns 取得,CursorAdapter 與 ContentUris 都依賴它。
  • 安全性:範例中的 SQL 皆以參數化方式組建,避免注入風險;若要對外開放 Provider,務必在 Manifest 中設定 android:exported 與讀寫權限。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved