3

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;
}
theapache64
  • 10,926
  • 9
  • 65
  • 108
Mark.222
  • 103
  • 1
  • 1
  • 8

1 Answers1

15

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

theapache64
  • 10,926
  • 9
  • 65
  • 108