我正在尝试使用 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 // first try
TrendingRepo: at position: 0 got item: 0pqcRzSd06WWlNNmcolu
TrendingRepo: at position: 1 got item: 7I7wiSYt5yEBWwN08bqJ
...
TrendingRepo: at position: 45 got item: 4B3dEPhFLqhKrYpLWYE7
TrendingRepo: at position: 46 got item: 4ddLqiGe8ReXW8SKq2Q6
TrendingRepo: at position: 47 got item: 4uVnnGNAmKvGUUHcV01n
TrendingRepo: pagination size : 48 // second try
//no more logging, data is empty
最佳答案
可能会出现项目小于分页大小的情况,所以这里是代码
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()
}
希望这对您有帮助。
关于java - Android - Firestore 使用 startAfter() 和 limit() 返回一个空查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56730559/