In this article let’s examine a few situations you might face while you are developing your app using ROOM database. Sometimes there is a need to change our database schema by adding fields or entities.
First of all, let’s assume that we have created an AppDatabase
with a data access object class UserDao
and a User
entity.
@Database(entities = arrayOf(User::class), version = 0)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}@Entity
data class User(@PrimaryKey val id: Int)
Database version unchanged
Let’s say that we want to add a field name
to the User
entity.
@Entity
data class User(@PrimaryKey val id: Int, val name: String)
If you leave unchanged the schema version but you modify the User
entity, when you will try to access your database, Room will throw an exception.
java.lang.IllegalStateException: Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the version number. You can simply fix this by increasing the version number.
Database version increased but no migration code provided
Now let’s increase the database version to 1 as suggested by the exception message.