2

I created a quiz like app where 10 questions are fetched once. If user got 8 marks out of 10. then I fetch next 10 questions. But startAfter always give the same response.

val questionCollectionRef = db.collection("questionCollection")
        ///.whereArrayContains("tags", tagName)
        .orderBy("questionID", Query.Direction.DESCENDING);
val id = SharedPrefs(this@McqActivity).read(OLD_DOCUMENT_ID, "")

if(id.isNotEmpty()){
    //questionCollectionRef.whereLessThan("questionID",id) //also tried for whereGreaterThan
    questionCollectionRef.startAfter(id);
    Log.v("startAfter","start After : " + id + "" );
}
questionCollectionRef.limit(10).get()
        //fixme  also orderBy date So user can see latest question first
        .addOnSuccessListener { querySnapshot ->
            if (querySnapshot.isEmpty()) {
                Log.d(TAG, "onSuccess: LIST EMPTY")
            } else {
                val questionList = querySnapshot.toObjects(QuestionBO::class.java)

                questionList.forEach { questionItem ->
                    resultList.add(ResultBO(questionItem))
                }

                if (resultList.size > 0) {
                    refreshQuestionWithData()
                }
            }
        }
        .addOnFailureListener { exception ->
            exception.printStackTrace()
        }

This code is written in Activity.After getting score above than 8 .

I open the same activity again and questionCollectionRef.startAfter called but still same question shown in Activity

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
  • @AlexMamo see the edit ..Next time when I open the activity It called startAfter method. But same record display – Zar E Ahmer Dec 15 '18 at 13:10

1 Answers1

4

When you call startAfter() (or any other query building methods), it returns a new query object. So you need to keep a reference to that object:

var questionCollectionQuery = db.collection("questionCollection")
        .orderBy("questionID", Query.Direction.DESCENDING);

val id = SharedPrefs(this@McqActivity).read(OLD_DOCUMENT_ID, "")
if(id.isNotEmpty()){
    questionCollectionQuery = questionCollectionQuery.startAfter(id);
    Log.v("startAfter","start After : " + id + "" );
}

questionCollectionQuery.limit(10).get()...

I also renamed questionCollectionRef to questionCollectionQuery, since the type after orderBy, startAfter or limit is a query.

Marco Hernaiz
  • 5,830
  • 3
  • 27
  • 27
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807