In my app I'm using Room with a prepopulated database myDatabase.db
which is then accessed using this code:
private val database = Room
.databaseBuilder(context.applicationContext, AppDatabase::class.java, dbName)
.createFromAsset("myDatabase.db")
.build()
The file myDatabase.db
is stored in the /assets/ folder. Then I had to add some new rows in one on my tables in such database. After that, I got an updated myDatabase.db
file, which I copied to the /assets/ folder replacing the old file. And here comes the problem: after installing the app, it still uses the old data. I did some searching but I only found results related to migrations. However, in my case, there is no change in the schema of the table, only some new rows are added. Furthermore, I don't understand why the app doesn't pick the new myDatabase.db
file and still uses the old one.
The only solution to get the app to use the new file myDatabase.db
was to uninstall the app and then install it again, but that's something I'd like to avoid. So, how can I change the file myDatabase.db
in assets folder and make the app pick the data in the new file through Room?
CodePudding user response:
Furthermore, I don't understand why the app doesn't pick the new myDatabase.db file and still uses the old one.
A Room database is persistent and lasts until it is deleted. createFromAsset will only be invoked when the database does not exist and hence why, under normal situations it will not replace the existing database.
A solution assuming that the App only reads the pre-populated daatbase is to:-
- add either of the
fallbackToDestructiveMigration
orfallbackToDestructiveMigrationFrom
- Increase the database version number
- DO NOT have a Migration that covers the old to new version
The migration instead of failing will delete the database and then attempt to create it. In doing so it will create the database from the new asset.