Prepolulating room database in android

Updated 1 March 2021

Save

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:-

Android Room Persistence Library

 

Android Room, Live Data And View Model

 

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 an app asset

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:-

 

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:-

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.

 

 

 

 

 

 

 

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home