How to populate Android Room database table on first run?

后端 未结 7 1911

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

7条回答
  •  囚心锁ツ
    2020-12-02 17:31

    I was struggling with this topic too and this solution worked for me:

    // build.gradle
    
        def room_version = "2.2.5"
    
        // Room
        implementation "androidx.room:room-runtime:$room_version"
        kapt "androidx.room:room-compiler:$room_version"
        implementation "androidx.room:room-ktx:$room_version"
    

    In your App class:

    // virtually create the db
            val db = Room.databaseBuilder(
                appContext, AppDatabase::class.java,
                Res.getString(R.string.dbname)
            ).createFromAsset(Res.getString(R.string.source_db_name)).build()
    
            // first call to db really creates the db on filesystem
            db.query("SELECT * FROM " + Room.MASTER_TABLE_NAME, null)
    

提交回复
热议问题