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

时间:2019-06-24 05:55:21

标签: java android firebase kotlin google-cloud-firestore

我正在尝试使用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 //第二次尝试

     

//没有更多日志记录,数据为空

1 个答案:

答案 0 :(得分:1)

在某些情况下,项目可能小于分页大小,因此代码如下

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

我希望这会对您有所帮助。