I'm developing an application with RoomDatabase that needs to pre-populate its data; I already managed to do it by adding the onCreate()
callback, but it gets called only when accessing the database the first time (like calling one of the Daos functions).
Is there any way to force the database creation without doing any read or write operation?
That's my code, MyDatabase.get()
is called in App.onCreate()
@Database(entities = {Entity1.class, Entity2.class}, version = 1, exportSchema = true)
public abstract class MyDatabase extends RoomDatabase {
private static MyDatabase sInstance;
public synchronized static TaxCodeDatabase get(Context context) {
if (sInstance == null) {
sInstance = buildDatabase(context);
}
return sInstance;
}
private static MyCodeDatabase buildDatabase(final Context context) {
return Room.databaseBuilder(context,
MyCodeDatabase.class,
"my-database")
.addCallback(new Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
sInstance.preFillData(context);
});
}
})
.build();
}
public abstract Entity1Dao entity2Dao();
public abstract Entity2Dao entity1Dao();
/**
* Populates the database with a series of initial data
*
* @param aContext
*/
public void prePopulateData(Context aContext) {
//Populate database here
}
See Question&Answers more detail:os