【发布时间】:2018-10-26 07:15:27
【问题描述】:
我有一个关于如何使用 Firestore 正确分页查询的问题。
通过将下一个查询放入上一个查询的 OnSuccessListener 中,就像在 Firestore 页面上的示例中一样,它不会不可避免地总是触发一次加载所有页面的连锁反应吗?这不是我们想要通过分页来避免的吗?
// Construct query for first 25 cities, ordered by population
Query first = db.collection("cities")
.orderBy("population")
.limit(25);
first.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot documentSnapshots) {
// ...
// Get the last visible document
DocumentSnapshot lastVisible = documentSnapshots.getDocuments()
.get(documentSnapshots.size() -1);
// Construct a new query starting at this document,
// get the next 25 cities.
Query next = db.collection("cities")
.orderBy("population")
.startAfter(lastVisible)
.limit(25);
// Use the query for pagination
// ...
}
});
来源:https://firebase.google.com/docs/firestore/query-data/query-cursors
这是我的方法。我知道在真正的应用程序中我应该使用RecyclerView,但我只想在TextView 上测试它。我想在每次单击按钮时加载 3 个文档。
将lastResult 存储为成员然后检查它是否不为空,看看它是否是第一个查询是否有意义?
public void loadMore(View v) {
Query query;
if (lastResult == null) {
query = notebookRef.orderBy("priority")
.orderBy("title")
.limit(3);
} else {
query = notebookRef.orderBy("priority")
.orderBy("title")
.startAfter(lastResult)
.limit(3);
}
query.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
String data = "";
for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
Note note = documentSnapshot.toObject(Note.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);
}
}
});
}
【问题讨论】:
-
你解决了吗?
-
有人告诉我我的方法很好
-
它对你有用吗?
-
是的,它正在工作
-
你的问题有确切的代码吗?
标签: java android firebase google-cloud-firestore