简体   繁体   中英

How to pre-populate data in Room Database

I am working on a contact application through a tutorial in Java. I was able to convert the convert to Kotlin until I started having issue with the AsyncTask to pre-populate data.

I confirm that I could send data to the Room database from the activity but nothing seem to be coming from pre-populated data.

Database

@Database(entities = [ContactEntity::class], version = 1, exportSchema = false)
abstract class ContactDatabase : RoomDatabase() {

    abstract fun getContactDao():ContactDao

    companion object{
        private var instance:ContactDatabase?=null

        @kotlin.UseExperimental(InternalCoroutinesApi::class)
        fun getInstance(context: Context): ContactDatabase {

            return instance?: synchronized(this){
                instance?: Room.databaseBuilder(context.applicationContext,
                    ContactDatabase::class.java, "contact_database")
                    .fallbackToDestructiveMigration()
                    .addCallback(roomCallBack)
                    .build()
            }
        }

        val roomCallBack = object: RoomDatabase.Callback(){
            override fun onCreate(db: SupportSQLiteDatabase) {
                super.onCreate(db)
                instance?.let { PopulateDbAsyncTask(it).execute() }
            }

        }

        internal class PopulateDbAsyncTask(db: ContactDatabase) : AsyncTask<Void, Void, Void>(){

            val contactDao = db.getContactDao()
            override fun doInBackground(vararg p0: Void?): Void? {
                contactDao.insert(ContactEntity("Darot", "Tosin", "M", "Atlantic View", "08060085192", R.drawable.maleavatar))
                contactDao.insert(ContactEntity("Tola", "Folawo", "M", "Atlantic View", "08060085192", R.drawable.femaleavatar))
                contactDao.insert(ContactEntity("Aisha", "Monday", "M", "Atlantic View", "08060085192", R.drawable.femaleavatar))
                return null
            }
        }
    }
}

MainActivity

class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

//        val contacts:ArrayList<ContactEntity>

        val contacts = arrayOf(

            ContactEntity("Tola", "Folawo", "M", "Atlantic View", "08060085192", R.drawable.femaleavatar),
            ContactEntity("Aisha", "Monday", "M", "Atlantic View", "08060085192", R.drawable.femaleavatar),
            ContactEntity("Darot", "Tosin", "M", "Atlantic View", "08060085192", R.drawable.maleavatar)
        )

        val arrayList: ArrayList<String> = ArrayList<String>(5)
        var list: MutableList<ContactEntity> = mutableListOf<ContactEntity>()

        list.add(ContactEntity("Tola", "Folawo", "M", "Atlantic View", "08060085192", R.drawable.femaleavatar))
        list.add(ContactEntity("Aisha", "Monday", "M", "Atlantic View", "08060085192", R.drawable.femaleavatar))
        list.add(ContactEntity("Darot", "Tosin", "M", "Atlantic View", "08060085192", R.drawable.maleavatar))

        val contactList = ArrayList<ContactEntity>()

        contactList.addAll(list)


        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.setHasFixedSize(true)
        val adapter = ContactAdapter()
        recyclerView.adapter = adapter


        val contactViewModel = ViewModelProviders.of(this).get(ContactViewModel::class.java)
        contactViewModel.getAllContactsModel().observe(this, object:Observer<List<ContactEntity>>{
            override fun onChanged(t: List<ContactEntity>) {
                adapter.setContacts(t)
                Toast.makeText(applicationContext, "$t", Toast.LENGTH_LONG).show()
            }
        })
    }
}

From the above code I am able to populate data manually into the Database. Where am I doing it wrong?

Room callbacks are not hit unless the table is read or written to. So doing ".build" never actually hits the callback. So a simple solution for this is to begin and end a transaction directly after building the table.

db.beginTransaction()
db.endTransaction()

Here is a link to a similar Stack Overflow question to help you: Room Database force OnCreate callback

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM