【问题标题】:startAfter not working in Firestore androidstartAfter 无法在 Firestore android 中工作
【发布时间】:2018-12-15 11:30:42
【问题描述】:

我创建了一个类似测验的应用程序,其中一次提取 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,但活动中仍然显示相同的问题

【问题讨论】:

  • @AlexMamo 看到编辑..下次我打开活动时它调用了 startAfter 方法。但同样的记录显示

标签: android firebase google-cloud-firestore


【解决方案1】:

当您调用startAfter()(或任何其他查询构建方法)时,它会返回一个新的查询对象。所以你需要保留对 that 对象的引用:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-28
    • 2021-01-21
    • 2019-03-13
    • 2020-07-24
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多