How to use Room Persistence Library with pre-populated database?

后端 未结 8 1051
别那么骄傲
别那么骄傲 2020-11-28 02:49

I\'d like to use Room with a pre-populated database, but I can\'t understand how to tell Room where to find my database.

I\'ve now put it in src/main/assets/da

8条回答
  •  [愿得一人]
    2020-11-28 02:57

    UPDATE (Nov 7th 2019)

    Room now supports using a pre-packaged database out of the box, since version 2.2.0

    https://developer.android.com/jetpack/androidx/releases/room#2.2.0

    Solution before version 2.2.0: Simple solution without any other external libraries.

    Room relies on the existing Android framework code to create or open a database. If you look into the source code of FrameworkSQLiteOpenHelper (Room's version of SQLiteOpenHelper) it internally calls SQLiteOpenHelper.getReadableDatabase() and other methods wherever needed.

    So, the simplest solution is to just copy the DB file from assets directory to mContext.getDatabasePath("my-database.sqlite") before creating the DB with Room.

    In your case, the code looks something like this -

    private final String DB_NAME = "my-database.sqlite";
    
    private MyDatabase buildDatabase(Context context) {
        final File dbFile = context.getDatabasePath(DB_NAME);
    
        if(!dbFile.exists()) {
            copyDatabaseFile(dbFile.getAbsolutePath());
        }
    
        return Room.databaseBuilder(context.getApplicationContext(),
            MyDatabase.class, DB_NAME)
            .build();
    }
    
    private void copyDatabaseFile(String destinationPath) {
        // code to copy the file from assets/database directory to destinationPath
    }
    

    This link has the code needed to copy the DB - link with code

提交回复
热议问题