首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 複製預置 SQLite 資料庫從 assets 到應用目錄:完整實作與錯誤排查

     編輯:程式設計綜合問答

常見錯誤

InputStream mInput = mContext.getAssets().open(DB_NAME); 拋出 IOException,導致跳入 catch 區塊。原因通常為:

  • 資料庫檔案未放在 assets/ 根目錄(或子目錄路徑不匹配)。
  • 檔名大小寫不符(Android assets 區分大小寫)。
  • APK 未包含該檔案(Build 清單檢查)。

完整可用方案

1. DatabaseHelper 核心類

public class DatabaseHelper extends SQLiteOpenHelper {
    private static String DB_NAME = "app.db";
    private static String DB_PATH = ""; // 運行時動態決定
    private final Context context;

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, 1);
        this.context = context;
        DB_PATH = context.getDatabasePath(DB_NAME).getParent() + "/";
    }

    public void createDatabase() throws IOException {
        if (!checkDatabase()) {
            getReadableDatabase(); // 建立空資料庫檔案
            close();
            copyDatabase();
        }
    }

    private boolean checkDatabase() {
        File dbFile = new File(DB_PATH + DB_NAME);
        return dbFile.exists();
    }

    private void copyDatabase() throws IOException {
        InputStream is = context.getAssets().open(DB_NAME);
        OutputStream os = new FileOutputStream(DB_PATH + DB_NAME);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }
        os.flush(); os.close(); is.close();
    }

    @Override public void onCreate(SQLiteDatabase db) {}
    @Override public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {}
}

2. 首次啟動初始化

// Application 或首個 Activity onCreate
DatabaseHelper helper = new DatabaseHelper(this);
try {
    helper.createDatabase();
} catch (IOException e) {
    e.printStackTrace();
}

3. 後續存取

SQLiteDatabase db = helper.getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM my_table", null);
// ...
c.close(); db.close();

進階:大型資料庫分割

若 assets 單檔超過 1MB(舊版 Android 限制),可將資料庫拆分為多個壓縮檔(.zip、.sqlite3.gz),首次啟動時解壓合併。

驗證技巧

  • 使用 adb shell 進入 /data/data/pkg/databases/ 檢查檔案大小。
  • 利用 sqlite3 指令開啟驗證表結構與資料。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved