Search code examples
android-studioandroid-room

Developing Android application with Room - why is database cleared between builds?


I'm following this course on use of Room in Android development: https://developer.android.com/codelabs/basic-android-kotlin-compose-update-data-room The DB class is defined to create a new DB only if one does not already exist:

@Database(entities = [Item::class], version = 1, exportSchema = false)
abstract class InventoryDatabase : RoomDatabase() {
    abstract fun itemDao(): ItemDao

    companion object {
        @Volatile
        private var Instance: InventoryDatabase? = null

        fun getDatabase(context: Context): InventoryDatabase {
            return Instance ?: synchronized(this) {
                Room.databaseBuilder(context, InventoryDatabase::class.java, "item_database")
                    .fallbackToDestructiveMigration()
                    .build()
                    .also { Instance = it }
            }
        }
    }
}

The DB version is never changed, nor are my DB, DAO, or Entity classes (which would change the schema). I presume that is what would trigger destructive migration.

Consequently, I would expect that once the DB is created, its content would persist. However, I find that when I rebuild my app and run it again, the content is (sometimes?) gone. Why would this be? Am I somehow cluttering the filesystem with DB instances (as far as I can tell, the Filesystem location Room uses by default requires root access, so I can't tell)?


Solution

  • Uncheck "clear app storage before deployment" in the run configuration. Screenshot: run configuration