1. SQLiteOpenHelper.onCreate
YES, there is Callback class for that.
You can add Callback to RoomDatabase.Builder like this
Room.databaseBuilder(getApplicationContext(), MyDb.class, "database-name")
.addCallback(new Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
//do something
}
@Override
public void onOpen(@NonNull SupportSQLiteDatabase db) {
super.onOpen(db);
//do something
}
})
.build();
2. SQLiteOpenHelper.onUpdate
YES, there is Migration class for that.
You can add Migration to RoomDatabase.Builder like this
Room.databaseBuilder(getApplicationContext(), MyDb.class, "database-name")
.addMigrations(MIGRATION_1_2, MIGRATION_2_3).build();
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(SupportSQLiteDatabase database) {
database.execSQL("CREATE TABLE `Fruit` (`id` INTEGER, "
+ "`name` TEXT, PRIMARY KEY(`id`))");
}
};
static final Migration MIGRATION_2_3 = new Migration(2, 3) {
@Override
public void migrate(SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE Book "
+ " ADD COLUMN pub_year INTEGER");
}
};
If app is upgrading database version 1 to 4.
- case A. if you have defined migrations for version 1 to 4.
- Boom. room will trigger only one migration code. version 1 to 4.
- case B. if you have defined migrations for version 1 to 2, version 2 to 3, version 3 to 4.
- room will trigger all migrations one after another.
you should check this documentation
Migrating Room databases
and this article
Understanding migrations with Room