0

I am developing an android app with post and comments using the firebase firestore database. In the comment section, I am loading the lastest 20 comments using the following code

        val db= FirebaseFirestore.getInstance()

        db.collection("comments")
            .whereEqualTo("post_id", postId)
            .limit(20)
            .orderBy("time", Query.Direction.DESCENDING)
            .get(Source.SERVER)
            .addOnSuccessListener { documents ->


            }
            .addOnFailureListener { exception ->

            }

I show these comments in recyclerview. When the user clicks previous comments I fetch timestamp of older comment and run following code

        val db= FirebaseFirestore.getInstance()

        db.collection("comments")
            .limit(20)
            .whereLessThan("time",timestamp)
            .whereEqualTo("post_id", postId)
            .orderBy("time", Query.Direction.DESCENDING)
            .get(Source.SERVER)
            .addOnSuccessListener { documents ->


            }
            .addOnFailureListener { exception ->

            }

it fetches 20 documents from firestore database. But it doesn't fetch older comment. Instead, it fetches the latest comments.

when I remove .orderBy("time", Query.Direction.DESCENDING) it loads very first comments from document for that post id

For example.If the post contains 60 comments. first, I want to load 60-40 comments. then I want to load 40-20. then 20-0 .

Akash kv
  • 429
  • 4
  • 13
  • 1
    For pagination you'll typically want to use the `startAt()`/`startAfter()` methods of the Firestore API, to which you can pass the anchor document. – Frank van Puffelen Apr 20 '19 at 14:29
  • can i pass document id instead of document? – Akash kv Apr 20 '19 at 16:17
  • Just the ID isn't enough. You need either a document instance or the fields that you order/filter on, plus the ID. See https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/Query.html#startAt(java.lang.Object...) – Frank van Puffelen Apr 20 '19 at 16:23
  • 1
    @Akashkv **[This](https://stackoverflow.com/questions/50741958/how-to-paginate-firestore-with-android)** is a recommended way in which you can paginate queries by combining query cursors with the limit() method. I also recommend you take a look at this **[video](https://www.youtube.com/watch?v=KdgKvLll07s)** for a better understanding. – Alex Mamo Apr 22 '19 at 07:40
  • Actually, I could make it work with pagination provided by firestore library. Thank you all – Akash kv Apr 22 '19 at 09:03

0 Answers0