How to Prepopulate Room Database in Android?
Room is one of the Jetpack Architecture Components in Android. This provides an abstract layer over the SQLite Database to save and perform the operations on persistent data locally. This is recommended by Google over SQLite Database although the SQLite APIs are more powerful they are fairly low-level, which requires a lot of time and effort to use. But Room makes everything easy and clear to create a Database and perform the operations on it. But what is meant by Prepopulating the database? Prepopulating the database means having some pre-loaded data in the database at the first run. So, We will see the implementation for prepopulating the Room database. We will Prepopulate the database from the app assets.
We need a pre-packaged database, which we will store in the assets folder in android studio.
To Prepopulate a room database from a pre-packaged database that is stored in assets, We need to call the createFromAsset( ) method from Room.databaseBuilder object. Now we will create the Data Entity. It will be a data class, let’s give it the name “Quote.kt”. Refer to the below code for reference.
(autoGenerate = true) is used to auto-increment to id whenever a new data is added.
Then we need to create Dao. Dao is an interface, So no need to define methods inside it. Room takes to care for implementation of these methods. Dao is used to accessing the data object in the database. Refer to the below code for reference.
Now we will create the database class, it is the main access point to the application’s persisted data. It is an abstract class, It extends to RoomDatabase. Here we call the createFromAsset(“path”) method from our Room.databaseBuilder object before calling build(). Refer to the below code for reference.
So, this is how we implement the Pre-populated Room persistence database.
Please Login to comment...