How to include a pre-populated database with Android app


#1

Hi Mr. Murphy,

I’m using Room in my Android app and want to include a pre-populated database file containing 200k+ rows with the app but am unable to figure out how to do it?
I’ve searched for a solution but none of them uses Room except this one library which I still need to give a try to.
I’ve also gone through this complaint filed by u which is still not resolved by Android team.
So, I just wanted to know if there is any workaround to use until a solid resolution is provided by Android team or is it simply impossible to do with a project using Room?

Regards,
Shahood


#2

See “Packing up a Room”, in Android’s Architecture Components. In Version 0.11 of that book, it appears starting on Page 251.

Admittedly, there are a couple of problems there:

  • I don’t explain too much about how my implementation works
  • My implementation uses SQLiteAssetHelper, which has been discontinued by its author

However, it demonstrates the basic concept. Somebody with time and inclination could create a better solution that blends the concepts from SQLiteAssetHelper directly into a SupportSQLiteOpenHelper implementation.


#3

I successfully bundled a pre populated database with the test version of my app in the following way:

    private static MyDatabase create(Context context) {
    final File dbFile = context.getDatabasePath(DB_NAME);

    if(!dbFile.exists()) {
        copyDatabaseFile(context, dbFile);
    }

    return Room.databaseBuilder(
            context.getApplicationContext(),
            MyDatabase.class, DB_NAME)
            .build();

    }

Here I’m using getDatabasePath() to retrieve, well, the database path. But in your feature request, u have requested some documented statement about where Room stores the database, or a method to retrieve that location.

All I wanted to ask is why u don’t consider getDatabasePath() as the method to retrieve that location. This method worked fine for my app but are there any cases where it could provide us with wrong database path in case we are using Room?
I want to follow the same methodology in the production version of my app but before going ahead, I would like to have your advice on how much of a risk is it to use getDatabasePath().

Thanks


#4

There is no requirement for FrameworkSQLite* classes to use that location. Right now, it happens to just pass your name to the framework SQLiteOpenHelper and related classes. It does not have to do that.

are there any cases where it could provide us with wrong database path in case we are using Room?

If they change the FrameworkSQLite* classes in a strange way, yes. Your approach is probably safe. I was seeking an official statement that is is safe.