我正在尝试使用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()
}
希望对您有帮助。