Room Database force OnCreate callback

Is there any way to force the database creation without doing any read or write operation?

No, sorry.

There is nothing stopping you from copying the pre-populated database into position before invoking Room, though. You would need to ensure that the pre-populated database has Room's metadata in it (e.g., by creating that database using Room itself).


It's took me a while to understand why a Room database is not populated with initial data after invoking .build() on a database builder.

As for me, it's really counter-intuitive that migrations and callbacks are triggered only on real read/write operation. Actually the issue caused by the reason that Room use class RoomOpenHelper which, as mentioned in documentation:

An open helper that holds a reference to the configuration until the database is opened.

As the result, configuration and all callbacks stored in the instance of RoomOpenHelper class while Sqlite's SQLiteOpenHelper, which actually performs database migrations, not created (lazy class loading in Java).

To overcome this behavior, any operation which cause getWritableDatabase() should be performed. I ended up with the following approach:

RoomDatabase db = Room.databaseBuilder(context,
            ...)
            .build();

  // and then
db.beginTransaction()
db.endTransaction()

  // or query a dummy select statement
db.query("select 1", null)

return db

After that the database will be created and populated with initial data.


Room version 2.2.0 (October 2019) introduced built-in methods for database's pre-population:

  1. From the prepackaged database file (*.db) that you should place inside assets/ directory.
  2. From the prepackaged database file (*.db) that you should place somewhere except assets/ directory.

For more details you can read official documentation.

For getting answer - how to prepare prepackaged database you can read this article in SO.