'Android Room DB Migration

Problem - Room DB getting wiped/cleared when doing force update play store update. I am working on a chat messenger application which uses Room DB as local database. Whenever I do a store update with increasing DB version, the local DB gets cleared and messages history are lost.

I'm Using Room DB. My Application is in the Play Store with the use of Room DB and the version is 4.

My Question is I'm changing the 9 tables schema, and now that I update the DB version, each table schema changes. Should I increase the DB version here? How can I accomplish this without losing the user data using Room DB for force update in Play Store? Ex. DB version is 4, I change the two tables’ elements like in the below query.

Do I need to increase DB version twice as two tables are changed or change to one number incremental will be fine? Example: Do I need DB to increase version to 6 OR keeping it 5 is enough?

private val mMigrationMessageStatus: Migration = object : Migration(4, 5) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE message_status RENAME TO MessageStatus")
                database.execSQL("ALTER TABLE MessageStatus ADD COLUMN userId TEXT NOT NULL default ''")
            }
        }
 private val mMigrationGroupMember: Migration = object : Migration(4, 5) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE group_member RENAME TO GroupMember")
                database.execSQL("ALTER TABLE GroupMember ADD COLUMN userId TEXT NOT NULL default ''")
            }
        }


return Room.databaseBuilder(context, AppDatabase::class.java, dbName)
                .allowMainThreadQueries()
                .addMigrations(mMigrationMessageStatus,mMigrationGroupMember)
                .build()



Solution 1:[1]

From room version 2.4.0, you can easily update using autoMigrations.

DATABASE CLASS

@Database(
    version = 3,
    autoMigrations = [
        AutoMigration(from = 1, to = 2),
        AutoMigration(from = 2, to = 3)
    ],
    .....
)

DATA CLASS

@Entity(tableName = "user")
data class DataUser(
    ....
    // I added this column, like this
    @ColumnInfo(defaultValue = "")var test: String = ""  
)

see reference below

android developer: room version2.4.0

android developer: autoMigration

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1