Why onCreate() of RoomDatabase.Callback() is not called?

Photo by Tim Gouw on Unsplash

Photo by Jørgen Håland on Unsplash

Room Persistence library is a part of android’s Jetpack components. It provides an abstraction layer over SQLite, which is also known as ORM(Object-relational Mapping).

RoomDB has substantially increased developer productivity by removing tons of boilerplate code and need to manage SQLite directly.

RoomDatabase.Callback()

One of the many features Room provides is the callbacks fun onCreate() and fun onOpen(). These methods come in handy when we want to pre-populate the database.

As simple as it might sound, it got tricky for me while using fun onCreate().

Trigger to onCreate()

As per the docs:

Called when the database is created for the first time. This is called after all the tables are created.

And it does exactly that, almost.

android:allowBackup=“true”

if you have android:allowBackup=“true” in your manifest, there’s a chance fun onCreate() might never get called.

Users might upgrade their device or just reinstall the app, in which case android system restores application-specific files including databases.

It can be solved by excluding databases from getting backed-up

<exclude domain=”database” path=”YourDatabase.db” />

Lazy Creation

RoomDB uses SQLiteOpenHelper class. SQLiteOpenHelper does not create database until getReadableDatabase() or getWriteableDatabase() is called.

As a result, the database is not really created until we fire a query or call a @Dao method.

So if you are pre-populating, it might be a good idea to immediately make a dummy query after calling build() function on database builder.

That’s all for now.

1 comments On Why onCreate() of RoomDatabase.Callback() is not called?

Leave a reply:

Your email address will not be published.

Site Footer

Sliding Sidebar