Database Create and Open Callbacks in Room
Using Room a database persistence library, you can not only build your apps fast and clean, but you can build reactive apps using room with other architectural component LiveData.
There are several articles and tutorials which can help you learn room and live data. Here are few links to room tutorials for your reference, https://developer.android.com/topic/libraries/architecture/index.html and http://www.zoftino.com/android-persistence-library-room.
One of the main task that is usually performed in any application is to run few scripts one time after database has been created or run scripts every time database is opened.
In this article, I’ll show how to execute scripts with Room after database has been created and run scripts every time data base is open.
First let’s see how this requirement can be accomplished using SQLite API. The main class in SQLite API that is used to get database and perform database operations is SQLiteOpenHelper. This class has onCreate and onOpen callback methods, which are called after database is created and every time database is opened respectively. You can override those methods as shown below to run scripts on those events.
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
private String sql;
MySQLiteOpenHelper(Context context, String dbName, String msql) {
super(context, dbName, null, 1);
sql = msql;
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(sql);
}
@Override
public void onOpen(SQLiteDatabase sqLiteDatabase) {
}
}Now let’s do the same with Room. Room provides RoomDatabase.Callback class, in latest version, that has onCreate and onOpen callback methods which are called when database is created and database is opened respectively. You need to implement those methods and add the callback class to RoomDatabase.Builder as shown below.
RoomDatabase.Callback implementation.
RoomDatabase.Callback rdc = new RoomDatabase.Callback(){
public void onCreate (SupportSQLiteDatabase db){
String SQL_CREATE_TABLE = “CREATE TABLE categories” +
“(“ +
“_id INTEGER PRIMARY KEY AUTOINCREMENT, “ +
“cat_name TEXT, “ +
“cat_type TEXT)”; db.execSQL(SQL_CREATE_TABLE); ContentValues contentValues = new ContentValues();
contentValues.put(“cat_name”, “electronics”);
contentValues.put(“cat_type”, “commerce”); db.insert(“categories”, OnConflictStrategy.IGNORE, contentValues);
Log.d(“db create “,”table created when db created first time in onCreate”);
} public void onOpen (SupportSQLiteDatabase db){
ContentValues contentValues = new ContentValues();
contentValues.put(“open_time”, date); db.insert(“dbusage”, OnConflictStrategy.IGNORE, contentValues);
Log.d(“db open “,”adding db open date record”);
}
};
Adding RoomDatabase.Callback to RoomDatabase.Builder
shopDatabase = Room.databaseBuilder(context,
ShopDatabase.class, “shop db”).addCallback(rdc).build();