-
Notifications
You must be signed in to change notification settings - Fork 23
Description
I was having an issue with RoomAsset not migrating the contents of my pre-loaded database to the usable Room database, so I dug through the code and found what I believe to be the culprit:
/**
* Open the database and copy it to data folder using [SQLiteAssetHelper]
*/
private fun openDb(context: Context, name: String, storageDirectory: String?, factory: SQLiteDatabase.CursorFactory?) {
val instantiated = "instantiated"
val sharedPref = context.defaultSharedPreferences
if (!sharedPref.getBoolean(instantiated, false)) {
SQLiteAssetHelper(context, name, storageDirectory, factory, 1).writableDatabase.close()
sharedPref.edit().putBoolean(instantiated, true).apply()
Log.w(TAG, "RoomAsset is ready ")
}
}
This method checks if there's a boolean value stored in SharedPreferences with the key "instantiated", and only migrates the contents if that value is false or does not yet exist. Now, my problem did not technically arise from trying to use multiple pre-populated databases, but rather from trying to overwrite the old one with one with a different name. However, I plan to have multiple in the future and can see the same problem arising - namely, that the database simply does not get filled in because RoomAsset thinks its job is already done.
I managed to work around it in my current situation by recording the name of my database myself in SharedPreferences, and resetting the "instantiated" key to false any time the name changes. However, it will become much more of a pain once I have multiple databases included, since I will have to keep resetting before initially migrating each one.
The problem stems from the quite non-descriptive and entirely non-unique key used for recording whether RoomAsset has initialized the database yet. Rather than simply "instantiated", it should be changed to something unique (both to RoomAsset, to prevent potential conflicts form other non-unique key values, and to the database, to allow multiple pre-populated databases without janky workarounds). For example, particularly since the name of the database is already passed to the method, this line:
val instantiated = "instantiated"
could be changed to something like:
val instantiated = "RoomAsset.instantiated." + name
This would be a super easy change, and if I had the time I'd just do a pull request for it but I don't for now.