How to extract the data list from the database in room database

Viewed 24

I am trying to make extract all the data in the database

private fun addRecord(donorDao:DonorDao){
        val Id:String=binding?.etDonorId?.text.toString()
        val bloodGr=binding?.etDonorBloodgroup?.text.toString()
        if(Id.isNotEmpty() && bloodGr.isNotEmpty()) {
            var mDonorList:ArrayList<String>?=null
            lifecycleScope.launch {
                donorDao.fetchAllDonor().collect {
                    var Donorlist = ArrayList(it)
                    for(item in Donorlist){
                        mDonorList?.add(item.id)
                    }
                }
            }
            if (checkduplicateId(mDonorList!!,Id)) {
                    lifecycleScope.launch {
                        donorDao.insert(DonorEntity(id = binding?.etDonorId?.text.toString(), bloodGroup = bloodGr))
                        Toast.makeText(
                            applicationContext,
                            "Record saved successfully",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }else {
                    Toast.makeText(applicationContext, "Duplicate Id!!", Toast.LENGTH_SHORT).show()
                }
        }else{
            Toast.makeText(this,"input is empty",Toast.LENGTH_SHORT).show()
        }
    }
    private fun checkduplicateId(mDonorList:ArrayList<String>,Id:String):Boolean{
        var i=true
        for(item in mDonorList!!){
            if(item==Id){
                i=false
                break
            }
            i=true
        }
        return i
    }

but in this code my Donor List is null I do not know where I am going wrong Is there any other way so that I can extract all the data in database in the array list? please help me

1 Answers

When you write mDonorList?.add(item.id) it's equivalent to writing

if(mDonorList != null){
    mDonorList.add(item.id)
}

and in your case, you initialized mDonorList to null. You should initialize it with var mDonorList : ArrayList<String> = emptyList()

Related