I've upgraded my app to feature a Room database. When the user upgrades to my new app version, I need to import data into the Room Database that was stored in other data structures. At first glance it looks like Room already supports this scenario:
db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "my-db")
.addCallback(new RoomDatabase.Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
// IMPORT DATA
}
})
.build();
However, when trying to actually import data, things get more complicated. When I try to import data using Entities, Daos and the AppDatabase, I run into an Exception:
java.lang.IllegalStateException: getDatabase called recursively
It doesn't seem to be possible to import data into the database using all the nice Room Entities, Daos and so forth. The onCreate
method does however provide access to the underlying SQLite database. Maybe I'm meant to import data there?
The documentation on using the SQLite database directly is rather thin. And it starts with a big red warning not to access the SQLite database directly but to use the Room abstractions instead!
How should I proceed? How is this usually done?
Do the tables I've defined with Entities already exist at this point? Or do I need to create the tables with SQL statements before I can start to import my data?