Search code examples
androiddatabasekotlinpseudocodedata-class

How to deal with changes when adding new field to a data class in Kotlin


I had this data class:

data class User(
  val name:String,
  val age: Int
)

I save users' data with this in my database, and now the problem is I want to add a new field

val gender: String

and if I added this the app crashed when retrieving users' data from the database because it is not the same data any more.

This is my code to retrieve data from the database:

@Query("SELECT*FROM users WHERE name =:name")
suspend fun getUser(name:String):Flow<User>

I would be most interested in seeing a pseudocode solution if possible.


Solution

  • You need to do a migration of your database. You can find all the instructions to do it there Migrating Room databases.

    If your room version is 2.4.0-alpha01 or higher:

    Replace in your database:

    @Database(
      version = 1,
      entities = {User.class}
    )
    

    with:

    @Database(
      version = 2,
      entities = {User.class},
      autoMigrations = {
        @AutoMigration (from = 1, to = 2)
      }
    )
    

    Else you will need to du the migration manually:

    Add this to your Database class:

    static final Migration MIGRATION_1_2 = new Migration(1, 2) {
      @Override
      public void migrate(SupportSQLiteDatabase database) {
        database.execSQL("ALTER TABLE users "
          + " ADD COLUMN gender TEXT");
      }
    };
    

    and add .addMigrations(MIGRATION_1_2) to your Room.databaseBuilder()