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);
}
});
}
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…