Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Room Persistence Library with pre-populated database?

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?

like image 714
Alberto Giunta Avatar asked May 30 '17 13:05

Alberto Giunta


People also ask

What is the main use case of persisting data locally using room library?

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.

Is room database persistent?

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.

What is room DB Android?

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.


1 Answers

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.

like image 96
Alberto Giunta Avatar answered Oct 05 '22 10:10

Alberto Giunta