Niyas
Niyas

Reputation: 767

Firestore realtime update is not working on recyclerview

I'm using cloud firestore to populate recyclerview.

However, the realtime update is not working, changes are shown after I restarting the app. I also added pagination on recyclerview. Document addition and modification are only shows when restarting the app.

To load my post:

private fun loadMorePost() {
    val nextQuery = shopsCollection
            .orderBy("timestamp", Query.Direction.DESCENDING)
            .startAfter(lastVisible)
            .limit(3)

    nextQuery.addSnapshotListener({ documentSnapshots, e ->
        if (!documentSnapshots.isEmpty) {

            lastVisible = documentSnapshots.documents[documentSnapshots.size() - 1]
            for (doc in documentSnapshots) {

                    val shop = doc.toObject(Shop::class.java)
                    shopList.add(shop)

                    mAdapter.notifyDataSetChanged()

                }
            }
    })
}

onStart():

public override fun onStart() {
    super.onStart()
    val user = FirebaseAuth.getInstance().currentUser
    val isUserFirstTime = java.lang.Boolean.valueOf(Utility.readSharedSetting(applicationContext, Utility.PREF_USER_FIRST_TIME, "true"))
    val introIntent = Intent(this@MainActivity, OnBoardActivity::class.java)
    introIntent.putExtra(Utility.PREF_USER_FIRST_TIME, isUserFirstTime)
    if (isUserFirstTime) {
        startActivity(introIntent)
        finish()
    } else if (user == null) {
        startActivity(Intent(this@MainActivity, WelcomeActivity::class.java))
        finish()
    } else if (!isUserFirstTime) {
        val firstQuery = shopsCollection.orderBy("timestamp", Query.Direction.DESCENDING).limit(3)
        firstQuery.addSnapshotListener({ documentSnapshots, e ->
            lastVisible = documentSnapshots.documents[documentSnapshots.size() - 1]

            for (doc in documentSnapshots) {
                showFabButton()
                val blogPost = doc.toObject(Shop::class.java)
                shopList.add(blogPost)

                mAdapter.notifyDataSetChanged()
              }
          })
       }
    }
 }

Upvotes: 3

Views: 3078

Answers (1)

Niels
Niels

Reputation: 499

I assume that the changes to the Database you refer to are deletions:

In your Code you add new items but don't remove possible deletions. So changing your code to the following should work:

nextQuery.addSnapshotListener({ documentSnapshots, e ->
    if (!documentSnapshots.isEmpty) {
        shopList.clear()
        lastVisible = documentSnapshots.documents[documentSnapshots.size() - 1]
        for (doc in documentSnapshots) {
                val shop = doc.toObject(Shop::class.java)
                shopList.add(shop)
                mAdapter.notifyDataSetChanged()
            }
        }
})

Upvotes: 2

Related Questions