1

I am trying to implement pagination functionality in android. Each time activity starts I want to fetch new 10 records from collection.

Next time when I open the activity. lastVisible (DocumentSnapshot ) must be saved in SharedPreference to get the new list.

        db = FirebaseFirestore.getInstance();

        //new code starts...
        Query first = null;

        if(new SharedPrefs(mContext).read("callForFristTime",true)){
            first = db.collection("questionCollection").whereEqualTo("questionType",1)
                    .orderBy("dateCreated")
                    .limit(numberOfQuestionFetched);

            new SharedPrefs(mContext).save("callForFristTime",false);
        }
        else{
            first = db.collection("questionCollection")
                    .whereEqualTo("questionType",1)
                    .orderBy("dateCreated")
                    .startAfter(lastVisible)//how could I save lastVisible
                    .limit(numberOfQuestionFetched);
        }

How to save DocumentSnapshot(lastVisible) in SharedPreference ?

Or tell another approach to handle pagination..

Problem Solved following this approach

Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
  • why not you add/save the query in sharedPreference or other any resource before closing the app? every when you open a app just get query string from and cast back to query and execute the event on it – Faiizii Awan Aug 25 '18 at 21:04
  • You can't Serialize a DocumentSnapshot. I'd look for another way to do this that doesn't require a full DocumentSnapshot that comes from somewhere other than a query itself. – Doug Stevenson Aug 25 '18 at 21:29
  • **[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 more details. – Alex Mamo Aug 27 '18 at 09:51
  • Have you tried to implement the solution from my answer in that post? – Alex Mamo Aug 27 '18 at 10:49
  • Your solution also requires lastVisible. But the next time I open the activity I don't have access to the lastVisible item. – Zar E Ahmer Aug 28 '18 at 10:31
  • 1
    Yeah, your best bet is to store `lastVisible.get("dateCreated")` and `lastVisible.getId()` and then next time do `.orderBy("dateCreated").orderBy(FieldPath.documentId()).startAt(lastVisibleDateCreated, lastVisibleId)` . This is functionally equivalent to using the lastVisible snapshot. – Michael Lehenbauer Sep 24 '18 at 21:32

0 Answers0