How to populate Android Room database table on first run?

后端 未结 7 1907

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

7条回答
  •  生来不讨喜
    2020-12-02 17:23

    You can populate tables after creating the database, make sure the operation is running on a separate thread. You can follow the classes bellow to pre-populate tables on the first time.

    AppDatabase.kt

    @Database(entities = [User::class], version = 1, exportSchema = false)
    abstract class AppDatabase : RoomDatabase() {
    
        abstract fun userDao(): UserDao
    
        companion object {
    
            // For Singleton instantiation
            @Volatile private var instance: AppDatabase? = null
    
            fun getInstance(context: Context): AppDatabase {
                return instance ?: synchronized(this) {
                    instance ?: buildDatabase(context).also { instance = it }
                }
            }
    
            private fun buildDatabase(context: Context): AppDatabase {
                return Room.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME)
                        .addCallback(object : RoomDatabase.Callback() {
                            override fun onCreate(db: SupportSQLiteDatabase) {
                                super.onCreate(db)
                                //pre-populate data
                                Executors.newSingleThreadExecutor().execute {
                                    instance?.let {
                                        it.userDao().insertUsers(DataGenerator.getUsers())
                                    }
                                }
                            }
                        })
                        .build()
            }
        }
    }
    
    

    DataGenerator.kt

    class DataGenerator {
    
        companion object {
            fun getUsers(): List{
                return listOf(
                    User(1, "Noman"),
                    User(2, "Aayan"),
                    User(3, "Tariqul")
                )
            }
        }
    
    }
    

提交回复
热议问题