0

I am using recyclerView to load data from Firestore. I want my recyclerView to get updated whenever a document gets added or deleted in the Firestore database without reloading the activity/fragment. Is there any way I can achieve this?

objects:

private var layoutManager: RecyclerView.LayoutManager? = null
private var adapter: RecyclerView.Adapter<RecyclerAdapter.ViewHolder>? = null
private lateinit var db: FirebaseFirestore
private lateinit var userArrayList: ArrayList<User>

its in fragment so

override fun onViewCreated(itemView: View, savedInstanceState: Bundle?) {
    super.onViewCreated(itemView, savedInstanceState)
    userArrayList = arrayListOf()
    eventChangeListener()

}

pulling data:

private fun eventChangeListener() {
    db = FirebaseFirestore.getInstance()
    db.collection("Users").addSnapshotListener(object : EventListener<QuerySnapshot>{
        override fun onEvent(value: QuerySnapshot?, error: FirebaseFirestoreException?) {
            if (error != null){
                Log.e("firestore error", error.message.toString())
                return
            }
            for (dc : DocumentChange in value?.documentChanges!!){
                if (dc.type == DocumentChange.Type.ADDED){
                    userArrayList.add(dc.document.toObject(User::class.java))
                }
            }
            callBack()
        }


    })
}

populating

private fun callBack() {
    holder.apply { //recycler view id
        layoutManager = GridLayoutManager(activity,2)
        adapter = RecyclerAdapter(userArrayList)
        this.adapter = adapter
    }
}
rhavelka
  • 2,283
  • 3
  • 22
  • 36
Omar Saleem
  • 137
  • 1
  • 3
  • 11
  • 2
    "Any ideas?" is not a great question for us to help with, as we have no way to know what the problem is. When you run this code, what doesn't work the way you expect it to? Even better: when you set a breakpoint on every line and then run in the debugger, which is the first line that doesn't do what you want it to do? – Frank van Puffelen Sep 30 '21 at 01:48
  • Yes indeed, what exactly in this code doesn't work the way you expect? – Alex Mamo Sep 30 '21 at 05:21
  • I want it to get updated as soon as the document get added/deleted in Firestore. so far its not updating until I refresh activity. sorry for if it wasn't clear – Omar Saleem Sep 30 '21 at 05:32
  • There is a very similar question in SO here [here](https://stackoverflow.com/questions/52483653/how-to-update-recyclerview-in-real-time-when-a-document-is-removed-from-firestor?rq=1) that you might find helpful. – Andrew Sep 30 '21 at 08:37

0 Answers0