问题
I have old project with Pre-loaded database in Assets folder. The project have SQLiteOpenHelper implemented for database operations. But now to update app I want to move my project to Room database library.
So my question is, Is there any method or feature available in Room library with I can use preloaded db file in app at runtime.
Or Is any way I can load db first and then from Room library I can directly execute queries on that db?
回答1:
Is there any method or feature available in Room library with I can use preloaded db file in app at runtime.
No more than there is with SQLite on Android. Just as you had to use some code there to copy the asset to the local filesystem, you have to do the same thing for Room.
This library appears to be based on SQLiteOpenHelper and is supposed to provide the hooks necessary to package a database as an asset, then use it with Room. I haven't tried it personally.
Also, this sample app demonstrates how to wrap SQLiteOpenHelper in the necessary classes to use it with Room. It is not especially straightforward.
回答2:
For future people possibly landing here like me in search of the answer - Room finally added the ability to load from assets as of 2.2.0-alpha01
Just put the database in assets folder (it can also be in a subfolder in assets) and access it like this:
val db = Room.databaseBuilder(applicationContext, MyDatabase::class.java, "database.db")
.createFromAsset("/databases/database.db")
.build()
If the database is not in a subdirectory, you just put the name without any additional path.
来源:https://stackoverflow.com/questions/49338939/room-library-can-copy-db-from-asset-folder