Search code examples
androidkotlinandroid-room

Room Database callback not working after version update


I am building an application that uses the Room library db and I ran into a small issue. In the first version when I create my database , I included a callback to populate my database so that I do not start with an empty database :

 @Provides
@Singleton
fun provideDatabase(app: Application , callback : MyDatabase.Callback) =
    Room.databaseBuilder(app , MyDatabase::class.java, "home_database")
        .fallbackToDestructiveMigration()
        .addCallback(callback)
        .build()

In this first version it worked fine then it got to a point whereby I had to add another table into the database. This meant that the schema changed and now I had to change the database version number from 1 to 2. After I changed the version number then ran the application , the callback I had seems not to work anymore , the database starts off empty. I initially thought the fallbackToDestructiveMigration() would prevent the database from losing its data and it will just recreate itself again with the callback working. Any clue of how I can get the callback back to working again?

Database code:

@Database(entities = [User::class , Result::class] , version = 2)
abstract class MyDatabase : RoomDatabase() {
    abstract fun dbDao() : Dao
    class Callback @Inject constructor(
        private val database : Provider<MyDatabase>,
        @ApplicationScope private val applicationScope: CoroutineScope
    ) : RoomDatabase.Callback(){

        override fun onCreate(db: SupportSQLiteDatabase) {
            super.onCreate(db)

            val dao = database.get().dbDao()

            applicationScope.launch {
                dao.addUser(
                    User(1 , "Larry" , "Android Developer","Boston" )
                )
                dao.addUser(
                    User(2 , "Garry" , "Javascript Developer","Casablanca" )
                )
           
            }
        }

    }

}


Solution

  • The onCreate() is not called on DestructiveMigration. You need to add onDestructiveMigration to your callback, just like onCreate:

    override fun onDestructiveMigration(db: SupportSQLiteDatabase) {
        super.onDestructiveMigration(db)
        // Add your data
    }
    

    See: https://developer.android.com/reference/androidx/room/RoomDatabase.Callback#onDestructiveMigration(androidx.sqlite.db.SupportSQLiteDatabase)