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

ContentProvider 與數據庫綁定及測試類的增刪改查驗證

編輯:關於 Android 程式設計

這篇整理兩件事:一是如何在 Activity 之間用 Intent 傳遞物件;二是如何把 ContentProvider 與 SQLite 數據庫綁定,並用測試類完整驗證增刪改查。

一、用 Intent 在畫面之間傳遞物件

兩個 Activity 跳轉時要帶一個自訂物件過去,做法是透過 Bundle,且實體類別必須實作 Serializable。

發送端:

// 定義一組靜態常量作為 key,避免字串寫錯
public final static String SER_KEY = "com.xiaoshu.worker";

Intent intent = new Intent();
intent.setClass(WorkerActivity.this, DisplayWorker.class);

Bundle bundle = new Bundle();
bundle.putSerializable(SER_KEY, worker);

intent.putExtras(bundle);
startActivity(intent);

接收端:

Worker worker = (Worker) getIntent().getSerializableExtra(WorkerActivity.SER_KEY);

把 key 定義成 public static final 常量並在兩邊共用,是避免 typo 的基本習慣。若物件內含大量資料或複雜結構,改用 Parcelable 效能會好很多,因為 Serializable 走的是反射序列化。

二、ContentProvider 與數據庫綁定

核心觀念:其他程式無法直接存取本程式的數據庫,但可以透過 ContentProvider 這個統一介面來讀寫。這正是它存在的目的——把數據存取包裝成標準化的 URI 操作。

實作分為四個部分。

1. 註冊 Provider

在 AndroidManifest.xml 的 <application> 節點內加入:

<provider
    android:name=".MyProvide"
    android:authorities="www.android1.com.cn"></provider>

authorities 是這個 Provider 的全域唯一標識,本質上就是 URI 的 authority 部分。多個 App 之間靠它互相定位。

2. MyProvide:繼承 ContentProvider

/**
 * 內容提供者與數據庫綁定。
 * 需註冊:<provider android:name=".MyProvide"
 *                  android:authorities="www.android1.com.cn"></provider>
 */
public class MyProvide extends ContentProvider {

    SQLiteDatabase db = null;

    @Override
    public boolean onCreate() {
        // 實例化數據庫並取得可寫連線
        MyDBHelper helper = new MyDBHelper(this.getContext());
        db = helper.getWritableDatabase();
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        // 查詢並回傳游標
        return db.query("Users", projection, selection, selectionArgs,
                        null, null, sortOrder);
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        db.insert("Users", "_id", values);
        return uri;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        return db.delete("Users", selection, selectionArgs);
    }

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

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

五個方法都是抽象方法,必須全部實作。實務上認真的做法會依 URI 路徑分派到不同的表,並在 getType 回傳正確的 MIME type(vnd.android.cursor.dir/... 或 vnd.android.cursor.item/...);這裡為了示範簡化了。

3. MyDBHelper:建立數據庫

public class MyDBHelper extends SQLiteOpenHelper {

    public MyDBHelper(Context context) {
        super(context, "szt.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // 建立 Users 表
        db.execSQL("create table Users(_id integer primary key autoincrement, name text)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 版本升級時的處理
    }
}

4. MainActivity:透過 ContentResolver 操作

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.sss_sss);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 取得內容解析器,透過它操作數據庫
                ContentResolver resolver = MainActivity.this.getContentResolver();
                Uri uri = Uri.parse("content://www.android1.com.cn");

                resolver.query(uri, null, null, null, null);

                ContentValues values = new ContentValues();
                values.put("name", "zhaoshan");
                resolver.insert(uri, values);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

關鍵在於:App 拿不到 SQLiteDatabase,只能拿 ContentResolver。insert 需要一個 ContentValues 物件承載要寫入的資料,query 則回傳 Cursor。

三、撰寫測試類驗證增刪改查

要測試「其他應用程式」的數據,步驟如下。

步驟 1:確認目標 Provider 的 authorities

也就是前面註冊的那串:www.android1.com.cn。

步驟 2:在測試專案的資源檔中加入 Instrumentation

在 Eclipse 中: AndroidManifest.xml → Application → Add → Instrumentation,設定:

  • Name:android.test.InstrumentationTestRunner
  • TargetPackage:com.example.testprovider(被測程式的套件名稱)

步驟 3:註冊測試資源檔

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <activity
        android:name="com.example.testprovider.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>

    <!-- 使用 Instrumentation 測試必須加上這行 -->
    <uses-library android:name="android.test.runner" />
</application>

步驟 4:繼承 AndroidTestCase 撰寫測試方法

public class TestMyProvide extends AndroidTestCase {

    ContentResolver resolver = null;

    @Override
    protected void setUp() throws Exception {
        resolver = this.getContext().getContentResolver();
        super.setUp();
    }

    public void testInsert() {
        ContentValues values = new ContentValues();
        values.put("name", "wangchenghua");
        resolver.insert(Uri.parse("content://www.android1.com.cn"), values);
        Log.i("msg", "wangchenghua");
    }

    public void testQuery() {
        Cursor c = resolver.query(Uri.parse("content://www.android1.com.cn"),
                null, null, null, null);
        while (c.moveToNext()) {
            Log.i("msg", c.getString(c.getColumnIndex("name")));
        }
        c.close();
    }

    public void testdelete() {
        resolver.delete(Uri.parse("content://www.android1.com.cn"),
                "_id = ?", new String[]{String.valueOf(1)});
    }

    public void testUpdate() {
        ContentValues values = new ContentValues();
        values.put("name", "wangxiaoou");
        resolver.update(Uri.parse("content://www.android1.com.cn"),
                values, "_id = ?", new String[]{String.valueOf(4)});
    }
}

步驟 5:執行與檢視結果

在 outline 檢視中會看到 setUp()、testInsert()、testQuery()、testdelete()、testUpdate() 五個方法。選中任一方法,右鍵 → Run As → Android JUnit Test 即可執行單一測試。

執行後可在 data/data/包名/ 下把數據庫檔案匯出(需 root 或用 adb pull 搭配 run-as),再用 SQLite 工具檢視內容。

四、幾個實務提醒

  • 測試方法必須以 test 開頭,且參數為無傳回值的 void,否則 JUnit 不會辨識。
  • setUp() 中呼叫 super.setUp() 的時機。範例中先取得 resolver 再呼叫 super,這是可行的;但若要依賴父類別初始化完成的狀態,應該把 super 放在前面。
  • insert 的 getWritableDatabase() 應在 onCreate 呼叫一次後重複使用,避免每次操作都重新開啟連線。
  • URI 格式:content:// 之後接 authorities,再接路徑。範例中沒有路徑段,正式專案通常會設計成 content://authority/table/id 這種結構,並在 query 裡用 UriMatcher 分派。
  • delete 與 update 的 selection 建議用參數化寫法("_id = ?" + selectionArgs),這不只是效能問題,更是防止 SQL 注入的必要習慣。範例中就是這樣寫的,請保持。
  • Provider 的 onCreate 在主程式啟動時就會被呼叫,不論有沒有人使用它,所以不要在裡面做太重的初始化。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved