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

Android 開發:把現成的 SQLite db 檔打包進 App 使用

編輯:關於 Android 程式設計

開發中有時候會拿到一份現成的 db 檔(例如離線字典、預設資料表),需要把它放進專案,再由程式複製到 App 的資料目錄中使用。

整個流程分兩步:先把檔案丟進 raw 資源目錄,再寫一段程式在首次啟動時把它複製出去。

DBOpenHelper 實作

public class DBOpenHelper {

    private final int BUFFER_SIZE = 400000;

    public static final String DB_NAME = "idiom.db";        // 保存的數據庫文件名
    public static final String PACKAGE_NAME = "cn.edu.bzu.happy";  // 應用的包名

    // 在手機裡存放數據庫的位置
    public static final String DB_PATH = "/data"
            + Environment.getDataDirectory().getAbsolutePath()
            + "/" + PACKAGE_NAME + "/databases";

    private Context context;

    public DBOpenHelper(Context context) {
        this.context = context;
    }

    public SQLiteDatabase openDatabase() {
        try {
            File myDataPath = new File(DB_PATH);
            if (!myDataPath.exists()) {
                myDataPath.mkdirs();   // 目錄不存在則建立
            }
            String dbfile = myDataPath + "/" + DB_NAME;

            if (!(new File(dbfile).exists())) {
                // 數據庫不存在,執行一次導入
                InputStream is = context.getResources().openRawResource(R.raw.idiom);
                FileOutputStream fos = new FileOutputStream(dbfile);

                byte[] buffer = new byte[BUFFER_SIZE];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.close();
                is.close();
            }

            return SQLiteDatabase.openOrCreateDatabase(dbfile, null);
        } catch (FileNotFoundException e) {
            Log.e("Database", "File not found");
            e.printStackTrace();
        } catch (IOException e) {
            Log.e("Database", "IO exception");
            e.printStackTrace();
        }
        return null;
    }
}

使用方式

public class TestDao {

    private DBOpenHelper dbHelper;

    public TestDao(Context context) {
        dbHelper = new DBOpenHelper(context);
    }

    public List<Test> getAllTests() {
        List<Test> tests = new ArrayList<Test>();
        SQLiteDatabase sqLiteDatabase = dbHelper.openDatabase();
        Cursor cursor = sqLiteDatabase.rawQuery("select * from test", null);

        while (cursor.moveToNext()) {
            // 在這裡取出各欄位資料,組裝成 Test 物件
        }
        cursor.close();   // 別忘了關閉
        return tests;
    }
}
TestDao test = new TestDao(context);
test.getAllTests();

幾個實務上的提醒

路徑選擇。範例中的 DB_PATH 指向內部儲存空間。註解裡也保留了 sdcard 的寫法,但在 Android 4.4(KitKat)之後,由於儲存權限模型收緊,寫入外部儲存的效果會與早期版本不同,檔案可能實際落在別的位置。若要在 4.4 以上寫入外部儲存,記得加上 WRITE_EXTERNAL_STORAGE 權限,並考慮改用 getExternalFilesDir() 取得 App 專屬目錄。

raw 資源的檔案格式。Android 的 aapt 在打包 raw 資源時,對某些副檔名會做壓縮處理,而 SQLite 檔一旦被壓縮就可能損壞。常見解法是把副檔名改為 aapt 不壓縮的形式,或在 build.gradle 中透過 aaptOptions { noCompress "db" } 明確排除。

版本升級。這個寫法只在檔案不存在時才複製,因此 App 升級換了新的 db 檔時不會生效。若需要支援,得額外比對版本號(例如用 SharedPreferences 記下上次複製的版本),版本不同時先刪除舊檔再重新複製。

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