Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate Android Room database table on first run?

In SQLiteOpenHelper there is a onCreate(SQLiteDatabase ...) method which i used to populate database tables with some initial data.

Is there a way to insert some data into Room database table on first app run?

like image 886
user2538289 Avatar asked Jun 22 '17 10:06

user2538289


People also ask

How do you pre populate a database?

Prepopulate from the file systembuild(); 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.

What is the difference between SQLite and room database in Android?

Room vs SQLiteRoom provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite. In the case of SQLite, There is no compile-time verification of raw SQLite queries. But in Room, there is SQL validation at compile time.


1 Answers

Updated

You can do this in 3 ways: important check this for migration details

1- Populate your database from exported asset schema

Room.databaseBuilder(appContext, AppDatabase.class, "Sample.db")     .createFromAsset("database/myapp.db")     .build(); 

2- Populate your database from file

Room.databaseBuilder(appContext, AppDatabase.class, "Sample.db")     .createFromFile(new File("mypath"))     .build(); 

3- You can run scripts after database is created or run every time database is opened using RoomDatabase.Callback, this class is available in the latest version of the Room library.

You need to implement onCreate and onOpen method of RoomDatabase.Callback and add it to RoomDatabase.Builder as shown below.

yourDatabase = Room.databaseBuilder(context, YourDatabase.class, "your db")     .addCallback(rdc)     .build();  RoomDatabase.Callback rdc = new RoomDatabase.Callback() {     public void onCreate (SupportSQLiteDatabase db) {         // do something after database has been created              }     public void onOpen (SupportSQLiteDatabase db) {         // do something every time database is open           } }; 

Reference

You can use Room DAO itself in the RoomDatabase.Callback methods to fill the database. For complete examples see Pagination and Room example

   RoomDatabase.Callback dbCallback = new RoomDatabase.Callback() {         public void onCreate(SupportSQLiteDatabase db) {             Executors.newSingleThreadScheduledExecutor().execute(new Runnable() {                 @Override                 public void run() {                    getYourDB(ctx).yourDAO().insertData(yourDataList);                 }             });         }     }; 
like image 135
Arnav Rao Avatar answered Sep 30 '22 11:09

Arnav Rao