【发布时间】:2021-01-21 09:23:42
【问题描述】:
我正在尝试将一个 Android Firestore 项目从 java 转换为 kotlin。但是陷入了分页部分,其中带有 java 代码的 startAfter(DocumentSnapshot) 工作正常。但是 kotlin 只给出前 3 个结果。 StartAfter(DocumentSnapshot) 部分不起作用。
如果您能指出我在 Kotlin 中哪里出了问题,那将非常有帮助。
这是完美运行的java代码
public void loadNotes(View v) {
Query query;
if (lastResult == null) {
query = notebookRef.orderBy("priority")
.limit(3);
} else {
query = notebookRef.orderBy("priority")
.startAfter(lastResult)
.limit(3);
}
Log.d(TAG, "loadNotes: "+ query);
query.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
String data = "";
for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
Notee note = documentSnapshot.toObject(Notee.class);
note.setDocumentId(documentSnapshot.getId());
String documentId = note.getDocumentId();
String title = note.getTitle();
String description = note.getDescription();
int priority = note.getPriority();
data += "ID: " + documentId
+ "\nTitle: " + title + "\nDescription: " + description
+ "\nPriority: " + priority + "\n\n";
}
if (queryDocumentSnapshots.size() > 0) {
data += "___________\n\n";
textViewData.append(data);
lastResult = queryDocumentSnapshots.getDocuments()
.get(queryDocumentSnapshots.size() - 1);
}
}
});
}
这是 Kotlin,它不起作用。
private fun loadNotes() {
val query = if (lastResult == null) {
notebookRef
.orderBy("priority")
.limit(3)
} else {
Log.d(TAG, "loadNotes: ${lastResult!!.id}")
notebookRef
.orderBy("priority")
.startAfter(lastResult)
.limit(3)
}
Log.d(TAG, "loadNotes: $query")
query.get()
.addOnSuccessListener { QuerySnapshot ->
var text = ""
for (queryDocumentSnapshot in QuerySnapshot) {
val note: Note = queryDocumentSnapshot.toObject(Note::class.java)
note.docID = queryDocumentSnapshot.id
val title = note.title
val description = note.description
val priority = note.priority
text += "ID: ${note.docID} \n Title : $title\n Description :$description\n" +
"Priority :$priority \n"
}
if (QuerySnapshot.size() > 0) {
text += "---------------\n\n"
textView_data.append(text)
lastResult = QuerySnapshot.documents[QuerySnapshot.size() - 1]
}
}
}
希望得到帮助
谢谢
测试所需代码:JavaActivityKotlinActivityNote Model和activity_main.xml
【问题讨论】:
-
对于真正的 kotlin 支持,您可以将
onSucessListeners替换为kotlin coroutines.here 是一个示例
标签: android kotlin google-cloud-firestore pagination