I'd like to use Room with a pre-populated database, but I can't understand how to tell Room where to find my database.
I've now put it in src/main/assets/databases
and when I create the instance for the Room database I create it this way:
Room.databaseBuilder( getApplicationContext(), AppDatabase.class, "justintrain.db" ) .allowMainThreadQueries() .build();
This way tho, I think it's creating a new database every time, or anyways, it's not using the pre-populated one.
How can I make it to find my database?
The most common use case is to cache relevant pieces of data so that when the device cannot access the network, the user can still browse that content while they are offline. The Room persistence library provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.
Room is a persistence library that's part of Android Jetpack. Room is an abstraction layer on top of a SQLite database. SQLite uses a specialized language (SQL) to perform database operations. Instead of using SQLite directly, Room simplifies the chores of setting up, configuring, and interacting with the database.
Room Database is a part of the Android Architecture components which provides an abstraction layer over SQLite which allows for more robust database access while still providing the full power of SQLite. Room is a persistence library, part of the Android Jetpack.
This is how I solved it, and how you can ship your application with a pre-populated database (up to Room v. alpha5)
put your SQLite DB database_name.db
into the assets/databases
folder
take the files from this repo and put them in a package called i.e. sqlAsset
in your AppDatabase
class, modify your Room's DB creation code accordingly:
Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "database_name.db") .openHelperFactory(new AssetSQLiteOpenHelperFactory()) .allowMainThreadQueries() .build();
Note that you have to use "database_name.db"
and not getDatabasePath()
or other methods: it just needs the name of the file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With