如何在房间数据库中预填充数据

时间:2019-12-19 17:35:33

标签: java android android-studio kotlin android-asynctask

我正在通过Java教程来开发联系人应用程序。我能够将转换成Kotlin的转换,直到我开始遇到AsyncTask的问题以预先填充数据。

我确认可以将活动中的数据发送到Room数据库,但似乎没有任何预填充数据。

数据库

@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()
            }
        })
    }
}

从上面的代码中,我能够手动将数据填充到数据库中。我在哪里做错了?

1 个答案:

答案 0 :(得分:0)

除非读取或写入表,否则不会命中房间回调。因此,执行“ .build”实际上不会碰到回调。因此,一个简单的解决方案是在建立表之后立即开始和结束事务。

db.beginTransaction()
db.endTransaction()

以下是指向类似堆栈溢出问题的链接,以帮助您:Room Database force OnCreate callback