Overall goal: Populating RecyclerView from Firebase with EventListener in ViewModel and Observer in Fragment. Issue is error in the Observer.
Image of error followed by code from ViewModel and Fragment.
Questions: Why does the “it” show as a MutableList instead of being wrapped in MutableLiveData? Is an observer the right way to keep the recyclerview data updated?
Spent several days trying to figure this out but not succeeding.
ViewModel:
init{
db = getDatabaseReference()
itemList = MutableLiveData(mutableListOf())
getContactsFromFirebase()
}
fun getContactsFromFirebase(): MutableLiveData<MutableList<DBClasses.contacts>> {
viewModel.db.child(“contacts”).addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
val contactList = mutableListOf<DBClasses.contacts>()
for (subSnapshot in snapshot.children) {
var authID = subSnapshot.key
for (contact in subSnapshot.children) {
var fbID = contact.key
var contactItem = DBClasses.contacts(
fb_auth_id = authID!!,
fb_contact_id = fbID!!,
user_id = contact.child(“user_id”).value.toString(),
contact_id = contact.child(“contact_id”).value.toString().toInt(),
status = contact.child(“status”).value.toString(),
addressee = contact.child(“addressee”).value.toString(),
first_name = contact.child(“first_name”).value.toString(),
last_name = contact.child(“last_name”).value.toString(),
address = contact.child(“address”).value.toString(),
city = contact.child(“city”).value.toString(),
state = contact.child(“state”).value.toString(),
zip_code = contact.child(“zip_code”).value.toString(),
timestamp_upload = contact.child(“timestamp_upload”).value.toString()
.toLong()
)
contactList.add(contactItem)
itemList.postValue(contactList)
}
}
}
}
override fun onCancelled(error: DatabaseError) {
Log.d(“cancelledevent”, “cancelled event fired”)
}
})
return itemList
}
Fragment:
var itemList = viewModel.getContactsFromFirebase()
itemList.observe(viewLifecycleOwner, Observer {
it?.let {
adapter.data = it
}
})
submitted by /u/mister-creosote
[link] [comments]