开始后无法在Firestore android中工作

时间:2018-12-15 11:30:43

标签: android firebase google-cloud-firestore

我创建了一个类似测验的应用程序,其中一次提取了10个问题。如果用户在10分中获得8分,那么我将提取下10个问题。但是 startAfter 总是给出相同的响应。

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()
        }

此代码写在Activity中,得分高于8之后。

我再次打开相同的活动,并questionCollectionRef.startAfter打电话,但仍显示在活动

中的相同问题

1 个答案:

答案 0 :(得分:0)

调用startAfter()(或任何其他查询构建方法)时,它将返回一个新的查询对象。因此,您需要保留对那个对象的引用:

val 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()...

我还将questionCollectionRef重命名为questionCollectionQuery,因为orderBystartAfterlimit之后的类型是查询。