How to pre-populate Room database at first run?

11,549

To insert data on first run / after db creation, you can use RoomDatabase.Callback.

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) {
        // ADD YOUR "Math - Sport - Art - Music" here
    }
    public void onOpen (SupportSQLiteDatabase db) {
        // do something every time database is open
    }
};

A complete example can be found here and detailed information about the callbacks here

Reference

Share:
11,549

Related videos on Youtube

Mark.222
Author by

Mark.222

Updated on June 04, 2022

Comments

  • Mark.222
    Mark.222 about 2 years

    I am creating an android app in java that uses room SQLite to store data. The app have two tables:

    • CoursesTable
    • StudentsTable

    I want to add default values for course_name entity so when the user open the app find the courses.

    For example :

    Math - Sport - Art - Music

    @Entity
    public class CoursesTable {
       @PrimaryKey(autoGenerate = true)
       int course_id;
       String course_name;
    }