I am trying to use Kotlin to:
- prepopulate the room database in my app from an existing SQL database.
- allow the user to update the data.
- let the updated data persist for the current version only.
- have the new version flush out the old data and replace it with the newly shipped SQL database.
Here's what I did so far:
I used createFromAsset
method to prepopulate the database with fallbackToDestructiveMigration()
call as follows:
@Database(entities = [MCData::class], version = 1, exportSchema = false)
abstract class MyRoom : RoomDatabase() {
abstract val myDao: MyDao
companion object {
@Volatile
private var INSTANCE: MyRoom? = null
fun getInstance(context: Context): MyRoom {
synchronized(this) {
var instance = INSTANCE
if (instance == null) {
instance = Room.databaseBuilder(
context.applicationContext,
MyRoom::class.java,
"mcdata.db")
.createFromAsset("mydata.db")
.fallbackToDestructiveMigration()
.build()
INSTANCE = instance
}
return instance
}
}
}
This is prepopulating the data and letting the user change it, but the updates in the data after the initial population are getting lost when the app restarts. I'm puzzled by this behavior, because it looks like the code is using the fallbackToDestructiveMigration()
to refresh the data even though the schema is not changed (the users can only change the values of two existing columns).
If I remove the fallbackToDestructiveMigration()
method, then the user's updates after initial pre-population persist, but when I reinstall the app with the new data, the database does not get updated.
Is there a way to have the data (including edits) persist in the current version, but gets replaced by the new pre-population SQL database when the new version is installed?