为了账号安全,请及时绑定邮箱和手机立即绑定

Firestore 使用 startAfter() 和 limit() 返回空查询

Firestore 使用 startAfter() 和 limit() 返回空查询

HUWWW 2023-02-16 16:45:56
我正在尝试使用 Firebase Firestore startAfter()和limit()查询方法实现分页系统。第一个查询成功返回,但第二个查询返回空快照。这是我的getNextPage()方法:fun getNextPage(paginationSize : Long) : TrendingRepository {database.collection("app")    .document("data")    .collection("offers")    .orderBy("discount")    .startAfter(lastVisible)    .limit(paginationSize)    .get().addOnSuccessListener { snapshot ->        Log.i("TrendingRepo", "pagination size : $paginationSize")        val newList = ArrayList<Offer>()        if (!snapshot.isEmpty) {            lastVisible = snapshot.documents[snapshot.size() - 1]        }        for (document in snapshot) {            val item = document.toObject(Offer::class.java)            newList.add(item)            Log.i("TrendingRepo", "at position: ${newList.indexOf(item)} got item: ${item.id}")        }        successListener?.onSuccess(newList)    }.addOnFailureListener {        failureListener?.onFailure(it.localizedMessage)    }return this}这是我的 Logcat:TrendingRepo: pagination size : 48 // 第一次尝试TrendingRepo:在位置:0 得到项目:0pqcRzSd06WWlNNmcoluTrendingRepo:在位置:1 得到了项目:7I7wiSYt5yEBWwN08bqJ...TrendingRepo:在位置:45 得到项目:4B3dEPhFLqhKrYpLWYE7TrendingRepo:在位置:46 得到项目:4ddLqiGe8ReXW8SKq2Q6TrendingRepo:在位置:47 得到项目:4uVnnGNAmKvGUUHcV01nTrendingRepo: pagination size : 48 // 第二次尝试//不再记录,数据为空
查看完整描述

1 回答

?
qq_笑_17

TA贡献1818条经验 获得超7个赞

可能存在项目小于分页大小的情况所以这里是代码


private var lastVisible: DocumentSnapshot? = null

private var isLastPage: Boolean = false

private var isDocEmpty: Boolean = false


var ref: Task<QuerySnapshot>? = null


 if (lastVisible != null) {

ref = database.collection("app").document("data").collection("offers").orderBy("discount").startAfter(lastVisible).limit(paginationSize).get()

 } else {

ref = database.collection("app").document("data").collection("offers").orderBy("discount").limit(paginationSize).get()

 }



 ref.addOnSuccessListener { documents ->


            hideProgress()

            isDocEmpty = documents.isEmpty




            if (!isDocEmpty) {

                lastVisible = documents.last()

                isLastPage = documents.size() < paginationSize

            }


            isLoading = false

        }

            .addOnFailureListener { exception ->

                Log.w("TAG", "Error getting documents: ", exception)

                isLoading = false

                hideProgress()

            }

我希望这会帮助你。


查看完整回答
反对 回复 2023-02-16
  • 1 回答
  • 0 关注
  • 131 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号