0
0
Android Kotlinmobile~3 mins

Why Database migrations in Android Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your app could upgrade its database without ever losing a single user's data?

The Scenario

Imagine you have an app with a database storing user info. You want to add a new feature that needs extra data fields. Without migrations, you must delete the old database and start fresh, losing all user data.

The Problem

Manually changing database structure is slow and risky. You might forget to copy data, cause app crashes, or confuse users with lost info. It's like remodeling a house by tearing down walls without a plan.

The Solution

Database migrations let you update your database step-by-step without losing data. They apply changes safely and automatically when the app updates, keeping user info intact and app stable.

Before vs After
Before
db.execSQL("DROP TABLE users")
db.execSQL("CREATE TABLE users (id INTEGER PRIMARY KEY)")
After
val MIGRATION_1_2 = object : Migration(1, 2) {
  override fun migrate(db: SupportSQLiteDatabase) {
    db.execSQL("ALTER TABLE users ADD COLUMN age INTEGER DEFAULT 0 NOT NULL")
  }
}
What It Enables

With migrations, your app can grow and improve its database without breaking or losing user data.

Real Life Example

A social app adds a new "last seen" timestamp to user profiles. Using migrations, it updates the database smoothly for millions of users without data loss or crashes.

Key Takeaways

Manual database changes risk data loss and app crashes.

Migrations update database safely and automatically.

Migrations keep user data intact during app upgrades.