簡體   English   中英

Android-Firestore使用startAfter()和limit()返回空查詢

[英]Android - Firestore returns an empty query using startAfter() and limit()

我正在嘗試使用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:分頁大小:48 //首先嘗試

TrendingRepo:在位置:0得到項目:0pqcRzSd06WWlNNmcolu

TrendingRepo:在位置:1得到了項目:7I7wiSYt5yEBWwN08bqJ

...

TrendingRepo:在位置:45得到項目:4B3dEPhFLqhKrYpLWYE7

TrendingRepo:在位置:46得到項目:4ddLqiGe8ReXW8SKq2Q6

TrendingRepo:在位置:47得到項目:4uVnnGNAmKvGUUHcV01n

TrendingRepo:分頁大小:48 //第二次嘗試

//不再記錄日志,數據為空

可能存在小於分頁大小的情況,因此代碼如下

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

希望對您有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM