Sobes.tech
Junior — Middle

How to implement database migration when using Room in Android?

sobes.tech AI

Answer from AI

To implement a database migration when using Room in Android, you need to:

  1. Create a new version of the database by increasing the version value in the @Database annotation.
  2. Define a migration class that implements the Migration interface, where you describe SQL commands for schema transformation in the migrate() method.
  3. Pass the migration object to the Room builder when creating the database via the addMigrations() method.

Example of migration from version 1 to 2:

val MIGRATION_1_2 = object : Migration(1, 2) {
    override fun migrate(database: SupportSQLiteDatabase) {
        database.execSQL("ALTER TABLE users ADD COLUMN age INTEGER DEFAULT 0 NOT NULL")
    }
}

val db = Room.databaseBuilder(context, AppDatabase::class.java, "app-db")
    .addMigrations(MIGRATION_1_2)
    .build()

Thus, when updating the version, Room will apply the migration and preserve the data.

How to implement database migration when using Room… - sobes.tech