How to put existing database in the .apk file?

前端 未结 3 960
再見小時候
再見小時候 2020-12-09 22:18

I have prebuild database of mostly string objects. I want to know how to put in my apk file so the database will be already created when the user installs the database.

3条回答
  •  粉色の甜心
    2020-12-09 22:37

    There are no any simple way to read database from assets directly. You should copy your database from assets to data folder in the first run, then when every time your app starts up, you should check database in the data folder and copy it again if the database does not exist.

    These steps help you:

    1) Execute these commands on your database, if android_metadata table does not exist in your database, android could not open your database.:

    CREATE TABLE android_metadata(locale TEXT DEFAULT 'en_US')
    INSERT INTO android_metadata VALUES('en_US')
    

    2) Chunk your database because android does not support reading a file that more than 1 MB size from assets.

    This python code chunks your database:

    def chunk_file(file_name):
        input_file = open(file_name, "rb")
    
        chunk_counter = 0;
        while True:
            chunk = input_file.read(512 * 1024) # 512 KB
            if chunk:
                output_file_name = file_name + "." + str(chunk_counter).zfill(4)
    
                output_file = open(output_file_name, "wb")
                output_file.write(chunk)
                output_file.close()
    
                chunk_counter += 1
            else:
                break
    
        input_file.close()
        return
    
    # Input: database.db
    # Output: database.db.0000, database.db.0001, database.db.0002, ...
    chunk_file("database.db")
    

    Then put database.db.0000, database.db.0001, database.db.0002, ... in the assets folder.

    3) Check database exists in the data folder when app starts up.

    public static boolean databaseExists() {
    
        boolean result = false;
    
        SQLiteDatabase checkDB = null;
    
        try {
            checkDB = SQLiteDatabase.openDatabase(
                    getApplicationContext().getFilesDir().getPath() + "/database.db",
                    null, SQLiteDatabase.OPEN_READONLY);
            result = true;
        } catch (SQLiteException exception) {
            result = false;
        }
    
        if (checkDB != null) {
    
            checkDB.close();
    
        }
    
        return result;
    }
    

    4) If database does not exist in data folder, copy database from assets to data folder.

    public static void copyDatabase() throws IOException {
        AssetManager assets = getApplicationContext().getAssets();
    
        // database.db.0000, database.db.0001, database.db.0002, ... --> databaseChunks.
        String[] databaseChunks = assets.list("");
        Arrays.sort(databaseChunks);
    
        OutputStream databaseStream = new FileOutputStream(
                getApplicationContext().getFilesDir().getPath() + "/database.db");
    
        for (int i = 0; i < databaseChunks.length; i++) {
            String databaseChunkName = databaseChunks[i];
    
            InputStream chunkStream = assets.open(databaseChunkName);
    
            int length;
            byte[] buffer = new byte[1024];
            while ((length = chunkStream.read(buffer)) > 0) {
                databaseStream.write(buffer, 0, length);
            }
    
            chunkStream.close();
        }
    
        databaseStream.close();
    
        return;
    }
    

    5) You can connect to the database now:

    SQLiteDatabase database = SQLiteDatabase.openDatabase(
                getApplicationContext().getFilesDir().getPath() + "/database.db",
                null, SQLiteDatabase.OPEN_READONLY);
    // ...
    database.close();
    

提交回复
热议问题