我正在尝试通过文档快照来使用分页来定义查询游标。
第一次打开片段时,在onCreateView中,我使用下面的代码从firestore获取7个事件
fun getAllSearchedEventsFromTheBeginning(startDate: Date, endDate: Date, selectedCity: String, selectedEventType: String, limit: Long, completion: (errorMessage:String?, events: ArrayList<Event>?, lastDocument: DocumentSnapshot?) -> Unit) {
// not only free events, paid events are also included
FirestoreCollectionReference.event.getReference()
.whereEqualTo(FIRESTORE_EVENT_FIELD_CITY,selectedCity)
.whereEqualTo(FIRESTORE_EVENT_FIELD_EVENT_TYPE, selectedEventType)
.whereEqualTo(FIRESTORE_EVENT_FIELD_HAS_BEEN_APPROVED,true)
.whereGreaterThan(FIRESTORE_EVENT_FIELD_DATE_START_TIME,startDate)
.whereLessThan(FIRESTORE_EVENT_FIELD_DATE_START_TIME,endDate)
.orderBy(FIRESTORE_EVENT_FIELD_DATE_START_TIME, Query.Direction.ASCENDING)
.limit(limit)
.get()
.addOnSuccessListener { snapshot ->
val lastDocument = snapshot.documents[snapshot.size() - 1]
val eventDocuments = snapshot.documents
val eventArray = ArrayList<Event>()
for (document in eventDocuments) {
val eventData = document.data
val event = Event(dataEvent = eventData)
eventArray.add(event)
}
completion(null,eventArray, lastDocument)
}.addOnFailureListener {
completion(it.localizedMessage,null,null)
}
}
我正在使用lamda表达式发送lastVisible文档,该lastVisible文档将用作下一个查询的起点
到达回收站视图的底部之后,我使用下面的代码从firestore中获取接下来的7个文档
fun getAllSearchedEventsAfterLastDocument(startDate: Date, endDate: Date, selectedCity: String, selectedEventType: String, limit: Long, lastDocument: DocumentSnapshot?, completion: (errorMessage:String?, events: ArrayList<Event>?, lastDocument: DocumentSnapshot?) -> Unit) {
// not only free events, paid events are also included
FirestoreCollectionReference.event.getReference()
.whereEqualTo(FIRESTORE_EVENT_FIELD_CITY,selectedCity)
.whereEqualTo(FIRESTORE_EVENT_FIELD_EVENT_TYPE, selectedEventType)
.whereEqualTo(FIRESTORE_EVENT_FIELD_HAS_BEEN_APPROVED,true)
.whereGreaterThan(FIRESTORE_EVENT_FIELD_DATE_START_TIME,startDate)
.whereLessThan(FIRESTORE_EVENT_FIELD_DATE_START_TIME,endDate)
.orderBy(FIRESTORE_EVENT_FIELD_DATE_START_TIME, Query.Direction.ASCENDING)
.limit(limit)
.startAfter(lastDocument)
.get()
.addOnSuccessListener { snapshot ->
val eventDocuments = snapshot.documents
if (eventDocuments.isEmpty()) {
completion("Event is empty",null, null)
} else {
val lastDocument = snapshot.documents.last()
val eventArray = ArrayList<Event>()
for (document in eventDocuments) {
val eventData = document.data
val event = Event(dataEvent = eventData)
eventArray.add(event)
}
completion(null,eventArray, lastDocument)
}
}.addOnFailureListener {
completion(it.localizedMessage,null,null)
}
}
我确定我向两个函数都发送了相同的参数, 并且最后一个文档也是正确的,它与我的“回收者”视图中显示的最后一个文档完全相同。
但是如果调用第二个功能getAllSearchedEventsAfterLastDocument
,下面的这一行总是在getAllSearchedEventsAfterLastDocument
中触发。
if (eventDocuments.isEmpty()) {
completion("Event is empty",null, null)
}
请帮助我,我很困惑。
答案 0 :(得分:0)
我终于找到了问题,
在.startAfter(lastDocument)
lastDocument
仍为可空类型(DocumentSnapshot?),应该不会。