startAfter not working in Firestore android

情到浓时终转凉″ 提交于 2020-06-29 05:48:26

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/53791952/startafter-not-working-in-firestore-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!