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

Android 跨應用資料庫訪問:ContentProvider 完整實作教學

編輯:關於 Android 程式設計

Android 每個應用的資料庫都是私有的,預設情況下別的 App 無法直接開啟你的 SQLite 檔案。當兩個 App(例如主程式與擴充套件、或開發者自己的兩個產品)需要共用同一份資料時,標準做法就是 ContentProvider:把資料庫包裝成一個統一的 URI 入口,讓讀寫都透過 ContentResolver 完成。

一、先定義契約類:把「常量」集中管理

URI、表名、欄位名、authority 這些字串會散落在多個檔案裡,一旦拼錯就是執行期崩潰。建議全部收在一個契約類(Contract)中,並把建構子設為 private,避免被實體化。

package com.example.providerdemo;

import android.net.Uri;

public final class UserContract {

    public static final String DB_NAME = "user_db";
    public static final String TABLE_NAME = "user";
    public static final int DB_VERSION = 1;

    public static final String COL_ID = "_id";
    public static final String COL_NAME = "username";
    public static final String COL_DATE = "date";
    public static final String COL_SEX = "sex";

    /** authority 必須全系統唯一,通常直接用應用包名 */
    public static final String AUTHORITY = "com.example.providerdemo";

    /** UriMatcher 使用的匹配碼 */
    public static final int CODE_USER = 1;
    public static final int CODE_USER_ID = 2;

    public static final String MIME_DIR = "vnd.android.cursor.dir/vnd.example.user";
    public static final String MIME_ITEM = "vnd.android.cursor.item/vnd.example.user";

    public static final Uri CONTENT_URI =
            Uri.parse("content://" + AUTHORITY + "/user");

    private UserContract() {}
}

二、資料庫幫助類

SQLiteOpenHelper 只負責建表與升級,不要在這裡寫業務邏輯。注意欄位型別:時間戳用 INTEGER 比 TEXT 更容易排序與比較。

package com.example.providerdemo;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DbHelper extends SQLiteOpenHelper {

    public DbHelper(Context context) {
        super(context, UserContract.DB_NAME, null, UserContract.DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + UserContract.TABLE_NAME + " ("
                + UserContract.COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + UserContract.COL_NAME + " TEXT NOT NULL,"
                + UserContract.COL_DATE + " INTEGER NOT NULL,"
                + UserContract.COL_SEX + " TEXT NOT NULL)");
    }

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

三、ContentProvider 的四個核心方法

Provider 需要實作 query、insert、update、delete、getType。所有方法的第一個參數都是 Uri,因此必須先用 UriMatcher 判斷「對方要的是整張表,還是某一筆特定記錄」。

package com.example.providerdemo;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.text.TextUtils;

public class UserProvider extends ContentProvider {

    private static final UriMatcher MATCHER = new UriMatcher(UriMatcher.NO_MATCH);

    static {
        MATCHER.addURI(UserContract.AUTHORITY, UserContract.TABLE_NAME,
                UserContract.CODE_USER);
        MATCHER.addURI(UserContract.AUTHORITY, UserContract.TABLE_NAME + "/#",
                UserContract.CODE_USER_ID);
    }

    private DbHelper mHelper;

    @Override
    public boolean onCreate() {
        mHelper = new DbHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        SQLiteDatabase db = mHelper.getReadableDatabase();
        Cursor cursor;
        switch (MATCHER.match(uri)) {
            case UserContract.CODE_USER:
                cursor = db.query(UserContract.TABLE_NAME, projection,
                        selection, selectionArgs, null, null, sortOrder);
                break;
            case UserContract.CODE_USER_ID:
                String id = uri.getPathSegments().get(1);
                String where = UserContract.COL_ID + " = ?"
                        + (TextUtils.isEmpty(selection) ? "" : " AND (" + selection + ")");
                cursor = db.query(UserContract.TABLE_NAME, projection, where,
                        prependId(id, selectionArgs), null, null, sortOrder);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        // 綁定通知 URI,資料變化時 Cursor 能自動刷新
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        if (MATCHER.match(uri) != UserContract.CODE_USER) {
            throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        SQLiteDatabase db = mHelper.getWritableDatabase();
        long rowId = db.insert(UserContract.TABLE_NAME, null, values);
        if (rowId <= 0) {
            throw new IllegalArgumentException("Insert failed: " + uri);
        }
        Uri result = ContentUris.withAppendedId(UserContract.CONTENT_URI, rowId);
        getContext().getContentResolver().notifyChange(result, null);
        return result;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        SQLiteDatabase db = mHelper.getWritableDatabase();
        int count;
        switch (MATCHER.match(uri)) {
            case UserContract.CODE_USER:
                count = db.update(UserContract.TABLE_NAME, values, selection, selectionArgs);
                break;
            case UserContract.CODE_USER_ID:
                String id = uri.getPathSegments().get(1);
                String where = UserContract.COL_ID + " = ?"
                        + (TextUtils.isEmpty(selection) ? "" : " AND (" + selection + ")");
                count = db.update(UserContract.TABLE_NAME, values, where,
                        prependId(id, selectionArgs));
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase db = mHelper.getWritableDatabase();
        int count;
        switch (MATCHER.match(uri)) {
            case UserContract.CODE_USER:
                count = db.delete(UserContract.TABLE_NAME, selection, selectionArgs);
                break;
            case UserContract.CODE_USER_ID:
                String id = uri.getPathSegments().get(1);
                String where = UserContract.COL_ID + " = ?"
                        + (TextUtils.isEmpty(selection) ? "" : " AND (" + selection + ")");
                count = db.delete(UserContract.TABLE_NAME, where,
                        prependId(id, selectionArgs));
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    @Override
    public String getType(Uri uri) {
        switch (MATCHER.match(uri)) {
            case UserContract.CODE_USER:
                return UserContract.MIME_DIR;
            case UserContract.CODE_USER_ID:
                return UserContract.MIME_ITEM;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
    }

    /** 把 Uri 中的 id 放到 selectionArgs 的最前面,全程使用佔位符避免 SQL 注入 */
    private String[] prependId(String id, String[] selectionArgs) {
        if (selectionArgs == null) {
            return new String[]{id};
        }
        String[] args = new String[selectionArgs.length + 1];
        args[0] = id;
        System.arraycopy(selectionArgs, 0, args, 1, selectionArgs.length);
        return args;
    }
}

四、在清單檔中註冊 Provider

註冊時的 android:authorities 必須和契約類裡的 AUTHORITY 完全一致,否則解析 URI 會失敗。若要讓「其他 App」也能訪問,Android 4.2 以上需明確加上 android:exported="true",並搭配讀寫權限控制。

<provider
    android:name=".UserProvider"
    android:authorities="com.example.providerdemo"
    android:exported="true"
    android:readPermission="com.example.providerdemo.READ"
    android:writePermission="com.example.providerdemo.WRITE" />

<permission
    android:name="com.example.providerdemo.READ"
    android:protectionLevel="signature" />
<permission
    android:name="com.example.providerdemo.WRITE"
    android:protectionLevel="signature" />

五、呼叫端:一律透過 ContentResolver

呼叫端不需要知道資料庫名稱、也不需要依賴 Provider 所在的程式,只要拿著 URI 操作即可。這正是跨項目共用的關鍵。

ContentResolver resolver = getContentResolver();

// 新增
ContentValues values = new ContentValues();
values.put(UserContract.COL_NAME, "carman lee");
values.put(UserContract.COL_DATE, System.currentTimeMillis());
values.put(UserContract.COL_SEX, "女");
Uri inserted = resolver.insert(UserContract.CONTENT_URI, values);

// 查詢全部
Cursor cursor = resolver.query(UserContract.CONTENT_URI,
        new String[]{UserContract.COL_NAME, UserContract.COL_DATE, UserContract.COL_SEX},
        null, null, UserContract.COL_DATE + " DESC");

List<String> rows = new ArrayList<>();
while (cursor.moveToNext()) {
    rows.add(cursor.getString(0) + " "
            + cursor.getString(1) + " "
            + cursor.getString(2));
}

// 更新指定 id
ContentValues update = new ContentValues();
update.put(UserContract.COL_NAME, "louis koo");
resolver.update(ContentUris.withAppendedId(UserContract.CONTENT_URI, inserted.getId()... ), update, null, null);

補充說明:ContentUris.parseUri(inserted, 1) 才是取出 id 的正確方式,上面最後一行僅示意「針對單筆記錄操作」的寫法,實作時請改用 long id = ContentUris.parseId(inserted); 再組出帶 id 的 Uri。

六、跨項目共用時的實務檢查清單

  • 兩個工程的契約類要維持一致,建議直接複製同一份 UserContract.java,避免欄位名不同步。
  • 呼叫方必須先安裝提供資料的 App,否則解析不到 authority。
  • 用到 android:grantUriPermissions 或 signature 權限時,兩邊的簽名檔要相同,否則權限不會生效。
  • Provider 方法會被多執行緒呼叫,資料庫操作請交由 SQLiteDatabase 自己排隊,不要在 Provider 裡額外維護可變狀態。
  • 記得在 Activity 生命週期結束時關閉 Cursor,或使用 startManagingCursor / try-with-resources(Cursor 實作 Closeable)避免洩漏。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved