2

Using Android API 32 and Room 2.4.2

Room database is created like this

companion object {
    @Volatile
    private var INSTANCE: AppDatabase? = null

    fun getDatabase(context: Context): AppDatabase {
        val tempInstance = INSTANCE
        if (tempInstance != null)
            return tempInstance
        synchronized(this) {
            val name = "mydb.db"
            val instance = Room.databaseBuilder(
                context.applicationContext,
                AppDatabase::class.java,
                name
            ).apply {
                fallbackToDestructiveMigration()
                createFromAsset(name)
            }.build()
            INSTANCE = instance
            return instance
        }
    }
}

The schema is version 1 and prepopulated db asset is version 0. When the app is started for the frist time the room db is created and populated with the asset data correctly. But whenever the app is restarted the room db is created and populated anew. If I change the prepopulated version to 1 then the recreation does not happen.

Why does it fallback to distructive and copy data when prepopulated version is less than the target one?

yaugenka
  • 2,602
  • 2
  • 22
  • 41

1 Answers1

0

The answer for your question hides within fallbackToDestructiveMigration() ;)

As stated in the documentation:

Allows Room to destructively recreate database tables if Migrations that would migrate old database schemas to the latest schema version are not found.

When the database version on the device does not match the latest schema version, Room runs necessary Migrations on the database.

If it cannot find the set of Migrations that will bring the database to the current version, it will throw an IllegalStateException.

You can call this method to change this behavior to re-create the database instead of crashing.

Note that this will delete all of the data in the database tables managed by Room.

This way every time you change you database version the database gets rebuild. You can also change your version number back and forth, so going from 1 to 2 and back to 1, if you like.

(to sum up: This possibly prevents memory leaks, some exceptions and also, prevents 2 databases with the same name and the same extension to exist at once)

JustSightseeing
  • 1,460
  • 3
  • 17
  • 37