Android Room Migration
In this tutorial, you'll learn about Android Room Migration. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
You roll out an app update and users hit IllegalStateException: Migration didn't properly handle — the app crashes, data is lost, or the Migration runs but columns are missing.
Wrong Approach ❌
// Automatic destructive migration — DROPS ALL DATA!
Room.databaseBuilder(context, AppDatabase::class.java, "my-db")
.fallbackToDestructiveMigration()
.build()
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE users ADD COLUMN age INTEGER")
// Forgot to handle the existing NOT NULL constraint
}
}
Output: User data wiped on every schema change. SQLiteException: Cannot add NOT NULL column with default value NULL.
Right Approach ✅
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(db: SupportSQLiteDatabase) {
// Step 1: Create new table with desired schema
db.execSQL("""
CREATE TABLE users_new (
id TEXT PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
age INTEGER NOT NULL DEFAULT 0
)
""")
// Step 2: Copy data from old table
db.execSQL("INSERT INTO users_new (id, name) SELECT id, name FROM users")
// Step 3: Drop old table
db.execSQL("DROP TABLE users")
// Step 4: Rename new table
db.execSQL("ALTER TABLE users_new RENAME TO users")
}
}
Output: Safe Migration preserving existing data with new schema.
Prevention
- Write
MigrationTestclasses usingRoom.inMemoryDatabaseBuilder. - Test both forward and backward migrations.
- For complex migrations, use the copy-drop-rename pattern.
- Never use
fallbackToDestructiveMigration()in production. - Annotate the
@DatabasewithexportSchema = trueand check in the JSON.
Common Mistakes with room Migration
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro