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

Android Content Provider(內容提供者)實作全流程

編輯:關於 Android 程式設計

一、什麼是內容提供者

ContentProvider 是 Android 四大組件之一,用來對外暴露應用自身的資料。當你希望自建的資料庫能被其他應用(或同一應用的不同模組)安全地讀取時,就該定義一個內容提供者,而不是直接把資料庫開給別人。

本文以一個「人員名冊」為例:先用 AndroidTestCase 灌入測試資料,再建立 Provider 對外提供查詢,最後示範外部如何取用。

二、用測試用例準備資料

1. 宣告 instrumentation,讓測試能掛在目標程式集上執行:

<instrumentation
    android:name="android.test.InstrumentationTestRunner"
    android:targetPackage="com.am.cpv" />
<uses-library android:name="android.test.runner" />

2. 建立資料庫輔助類,負責建表與版本升級:

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

public class MyDBOpenHelper extends SQLiteOpenHelper {
    public MyDBOpenHelper(Context context) {
        super(context, "person.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table person (id integer primary key autoincrement,"
                 + "name varchar(20), number varchar(20))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 依需求處理表結構變更
    }
}

3. 撰寫 AndroidTestCase,一次寫入 30 筆資料,並驗證查詢結果:

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.test.AndroidTestCase;
import com.am.cpv.db.MyDBOpenHelper;

public class AddDataTestCase extends AndroidTestCase {

    public void testAdd() {
        MyDBOpenHelper oh = new MyDBOpenHelper(getContext());
        SQLiteDatabase wdb = oh.getWritableDatabase();
        for (int i = 0; i < 30; i++) {
            ContentValues values = new ContentValues();
            values.put("name", "name" + i);
            values.put("number", "110-" + i);
            wdb.insert("person", null, values);
        }
        wdb.close();
    }

    public void testQuery() {
        MyDBOpenHelper oh = new MyDBOpenHelper(getContext());
        SQLiteDatabase rdb = oh.getReadableDatabase();
        Cursor cursor = rdb.query("person", null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            for (String colName : cursor.getColumnNames()) {
                int index = cursor.getColumnIndex(colName);
                System.out.print(cursor.getString(index) + " ");
            }
            System.out.println();
        }
        cursor.close();
    }
}

三、建立內容提供者

1. 繼承 ContentProvider。關鍵在於用 UriMatcher 註冊一組「權限名稱 + 路徑」的對應關係,並在 query() 中判斷來源:

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;
import com.am.cpv.db.MyDBOpenHelper;

public class PersonProvider extends ContentProvider {

    private static final int QUERY = 1;
    private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    private MyDBOpenHelper helper;

    static {
        uriMatcher.addURI("com.am.persionProvider", "query", QUERY);
    }

    @Override
    public boolean onCreate() {
        helper = new MyDBOpenHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        if (uriMatcher.match(uri) == QUERY) {
            SQLiteDatabase db = helper.getReadableDatabase();
            return db.query("person", projection, selection,
                    selectionArgs, null, null, sortOrder);
        }
        return null;
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        return null;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        return 0;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        return 0;
    }
}

2. 在 AndroidManifest.xml 中註冊。authorities 必須與 UriMatcher 中使用的字串完全一致,exported 決定是否允許外部應用存取:

<provider
    android:name="com.am.cpv.pv.PersonProvider"
    android:authorities="com.am.persionProvider"
    android:exported="true" />

四、外部如何讀取資料

呼叫端不需要知道資料庫的存在,只要透過 ContentResolver 加上 URI 即可:

public void click(View v) {
    ContentResolver cr = getContentResolver();
    Uri uri = Uri.parse("content://com.am.persionProvider/query");
    Cursor cursor = cr.query(uri, null, "name=?", new String[] { "name1" }, null);
    while (cursor.moveToNext()) {
        for (String colName : cursor.getColumnNames()) {
            int index = cursor.getColumnIndex(colName);
            System.out.print(cursor.getString(index) + " ");
        }
    }
    cursor.close();
}

整條資料流因此變得清楚:TestCase 負責鋪資料,Provider 負責開一個受控的出入口,呼叫端只認 URI 與欄位名稱,彼此完全解耦。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved