Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

Android 資料庫實作指南:用 Adapter 封裝 SQLite 操作

編輯:進階開發

操作 Android 資料庫時,有兩個實務原則值得牢記:第一,廣播 action 必須名副其實;第二,為資料庫互動建立一層包裝。本文說明這兩個原則,並提供一個可直接套用的資料庫 Adapter 骨架。

原則一:action 要名副其實

強烈建議,當你接收或發出一個系統 action 時,做的要是名副其實的事。例如你回應一個 VIEW 動作,做的卻是編輯;或你送出一個 PICK 訊息,其實想讓對方執行編輯。這些都會造成語意混亂,讓組件之間的匹配變得不可預期。

原則二:建立資料庫 Adapter

一個好習慣是建立輔助類來簡化資料庫互動。具體做法是建立一個資料庫 Adapter,為資料庫操作加上一層包裝。它應該提供直觀、強型別的方法,如新增、刪除、更新項目;同時負責查詢,以及建立、開啟與關閉資料庫的包裝。

此外,它常用靜態常數來定義表名、欄名與欄位索引。下面的程式碼片段展示了一個標準資料庫 Adapter 類的骨架,其中包含一個擴充 SQLiteOpenHelper 的內部類,用於簡化資料庫的開啟、建立與升級。

import android.content.Context;
import android.database.*;
import android.database.sqlite.*;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

public class MyDBAdapter {

    // 每個欄位的名稱與索引
    public static final String KEY_NAME = "name";
    public static final int NAME_COLUMN = 1;

    // TODO: 為資料表中的每個欄位建立 public 常數

    // 建立資料庫的 SQL 敘述
    private static final String DATABASE_CREATE = "create table "
        + DATABASE_TABLE + " (" + KEY_ID
        + " integer primary key autoincrement, "
        + KEY_NAME + " text not null);";

    // 資料庫實例
    private SQLiteDatabase db;

    // 使用資料庫的應用 context
    private final Context context;

    // 資料庫開啟/升級輔助類
    private myDbHelper dbHelper;

    public MyDBAdapter(Context _context) {
        context = _context;
        dbHelper = new myDbHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public MyDBAdapter open() throws SQLException {
        db = dbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        db.close();
    }

    public long insertEntry(MyObject _myObject) {
        ContentValues contentValues = new ContentValues();
        // TODO 填入代表新列的 ContentValues
        return db.insert(DATABASE_TABLE, null, contentValues);
    }

    public boolean removeEntry(long _rowIndex) {
        return db.delete(DATABASE_TABLE, KEY_ID + "=" + _rowIndex, null) > 0;
    }

    public Cursor getAllEntries() {
        return db.query(DATABASE_TABLE, new String[] {KEY_ID, KEY_NAME},
                null, null, null, null, null);
    }

    public MyObject getEntry(long _rowIndex) {
        MyObject objectInstance = new MyObject();
        // TODO 回傳指向該列的 Cursor,並用其值填充 MyObject
        return objectInstance;
    }

    public int updateEntry(long _rowIndex, MyObject _myObject) {
        String where = KEY_ID + "=" + _rowIndex;
        ContentValues contentValues = new ContentValues();
        // TODO 依新物件填入 ContentValues
        return db.update(DATABASE_TABLE, contentValues, where, null);
    }

    private static class myDbHelper extends SQLiteOpenHelper {

        public myDbHelper(Context context, String name,
                CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        // 當資料庫不存在時呼叫,用於建立新庫
        @Override
        public void onCreate(SQLiteDatabase _db) {
            _db.execSQL(DATABASE_CREATE);
        }

        // 當資料庫版本升級時呼叫
        @Override
        public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
            // TODO 實作版本升級邏輯
        }
    }
}

為什麼值得多寫這一層

把資料庫細節收攏在 Adapter 裡,上層程式碼只需要呼叫 insertEntry、removeEntry、updateEntry 這類語意明確的方法,不必處理由 SQL 字串拼接帶來的錯誤與安全性風險。當資料表結構需要調整時,你也只需要改一處——這個成本,遠低於讓資料庫邏輯散落在各個 Activity 之中。

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