Raghu Krishnan R
Raghu Krishnan R

Reputation: 312

how to add query in to setup queries room database for populate db with some inital value

I am trying to add Room DB in my app. I need to add some master data in my table while init the db. Is there any way to do that like addSetUpQuery()

Room.databaseBuilder(appContext, KeepiDB::class.java, DATABASE_NAME)
                .addMigrations(MIGRATION_2_3)
                .addSetUPQuery("Query here")
                .build()

Upvotes: 0

Views: 389

Answers (1)

M D
M D

Reputation: 47817

I saw you basic way of how you can do?

Init Room Database like below

 val instance = Room.databaseBuilder(
                    context.applicationContext,
                    WordRoomDatabase::class.java,
                    "Word_database"
                ).addCallback(WordDatabaseCallback()).build() // set my own callback here

And implement WordDatabaseCallback like

private class WordDatabaseCallback(
        private val scope: CoroutineScope
    ) : RoomDatabase.Callback() {

        override fun onOpen(db: SupportSQLiteDatabase) {
            super.onOpen(db)
            INSTANCE?.let { database ->
                scope.launch(Dispatchers.IO) {
                    populateDatabase(database.wordDao())
                }
            }
        }

        suspend fun populateDatabase(wordDao: WordDao) {

            //Clearing all the data from table  
            wordDao.deleteAll()

            //Adding record 
            var word = Word("Hello")
            wordDao.insert(word)

            //Adding record 
            word = Word("World!")
            wordDao.insert(word)
        }
    }

WordDao is my DAO and I am trying insert/delete data via it

For more details you can see below links

  1. Link1
  2. Link2
  3. Link3

Upvotes: 1

Related Questions