How to populate Android Room database table on first run?

后端 未结 7 1898

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

7条回答
  •  一向
    一向 (楼主)
    2020-12-02 17:24

    There are 3 ways of prepopulating of db
    The first 2 is coping from assets and file which is described here
    The third way is programmatical after db creation

    Room.databaseBuilder(context, Database::class.java, "app.db")
        // ...
        // 1
        .createFromAsset(...)
        // 2
        .createFromFile(...)
        // 3
        .addCallback(DatabaseCallback())
        .build()
    

    Here is the manual filling

    class DatabaseCallback : RoomDatabase.Callback() {
    
        override fun onCreate(db: SupportSQLiteDatabase) = db.run {
            // Notice non-ui thread is here
            beginTransaction()
            try {
                execSQL(...)
                insert(...)
                update(...)
                delete(...)
                setTransactionSuccessful()
            } finally {
                endTransaction()
            }
        }
    }
    

提交回复
热议问题