In android, We can store data locally in order to show it to the user offline and perform important functions. We can store data in android in two major way:-
1: Share Preference
2: Implementing Local Database
We are using Room DataBase in order to the local database. In this blog, We will learn how to prepopulate room data. If you want to know how to implement room datbase in android.
You can go through the following blogs:-
In Room from 2.2.0 and higher, there is an option to use the API method in order to populate the database. We can prepopulate the room database by two way:-
Prepopulate from the file system
1: Prepopulate from an app asset
For prepopulating the database using this method, We have to locate the file anywhere in the app’s asset directory. Then we can pass the path in our kotlin class like this:-
1 2 3 |
Room.databaseBuilder(appContext, AppDatabase.class, "Sample.db") .createFromAsset("database/myapp.db") .build() |
2: Prepopulate from the file system
In order to prepopulate the database using the file system, We have to locate the file anywhere in the app’s asset directory. Then we can pass the path in our kotlin class like this:-
1 2 3 |
Room.databaseBuilder(appContext, AppDatabase.class, "Sample.db") .createFromFile(File("mypath")) .build() |
The createFromFile() method accepts a File argument for the prepackaged database file. Room creates a copy of the designated file rather than opening it directly,
so make sure your app has read permissions on the file.
Note: When prepopulating from the file system, Room validates the database to ensure that its schema matches the schema of the prepackaged database.
You should export your database’s schema(https://developer.android.com/training/data-storage/room/migrating-db-versions#export-schema)
to use as a reference as you create the prepackaged database file.
Hope you have enjoyed the blog. In order to get more information about it, you can go through the following link:-
https://developer.android.com/training/data-storage/room/prepopulate#kotlin
Thanks for the reading.