How To Import Data Into A Room Database Upon Creation?
Solution 1:
There are basically two ways to import data into a Room database upon creation. The first uses an ugly workaround but then allows you to use Room Entities and all. The second is to work directly with the SQLiteDatabase instance provided.
1. Insert a guard and work with Room abstractions
finalboolean[] doImport = { false };
db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "my-db")
.addCallback(newRoomDatabase.Callback() {
@OverridepublicvoidonCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
doImport[0] = true;
}
})
.build();
db.userDao().get(17);
if (doImport[0]) {
UserEntityuser=newUserEntity();
user.name = "John Doe";
db.userDao().insert(user);
}
The doImport
boolean serves as a guard to protocol, whether the onCreate
callback has been called. It needs to be an array though, because a new value couldn't be assigned to a simple boolean from within onCreate
.
Notice also the seemingly senseless line db.userDao().get(17);
. It is necessary to access the database in order for the onCreate
callback to be called. Otherwise doImport
would remain false
at this point, regardless of whether or not the database was newly created.
Finally in the last if
block the database may be accessed with all the nice abstractions Room provides.
2. Work with the SQLiteDatabase directly
db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "my-db")
.addCallback(newRoomDatabase.Callback() {
@OverridepublicvoidonCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
db.beginTransaction();
ContentValuesvalues=newContentValues();
values.put("name", "John Doe");
db.insert("UserEntity", SQLiteDatabase.CONFLICT_ABORT, values);
db.setTransactionSuccessful();
db.endTransaction();
}
})
.build();
A lot less painful then I suspected. You need to work with strings though to identify database tables and fields, which is error prone!
Post a Comment for "How To Import Data Into A Room Database Upon Creation?"