android - 从 firestore 获取最后 25 条聊天消息(文档)?(安卓/Java)
问题描述
我有一个聊天应用程序,我想:
- 获取最后 25 条消息
- 按升序排序。
代码:(不工作)
firebaseFirestore.collection("chats")
.document(chatUid).collection("allchats")
.orderBy("chat_datesent",Query.Direction.DESCENDING)
.limit(25)
.orderBy("chat_datesent",Query.Direction.ASCENDING)
.addSnapshotListener(new EventListener<QuerySnapshot>() {
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots,Nullable FirebaseFirestoreException e) {
if (queryDocumentSnapshots != null) {
String dated;
for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {
//body
}
}
});
在这里,我尝试使用第一个OrderBy
来获取最后 25 个文档,因为limittolast()
在 Firestore 中是不可能的。
我怎样才能做到这一点?我必须使用复合索引吗?
请帮忙。
解决方案
您可以使用Ashish 的 answer获取最后 25 条消息,并且您可以在收到数据后对聊天列表进行排序
firebaseFirestore.collection("chats")
.document(chatUid).collection("allchats")
.orderBy("chat_datesent", Query.Direction.DESCENDING)
.limit(25)
.addSnapshotListener(new EventListener<QuerySnapshot>() {
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, Nullable FirebaseFirestoreException e) {
if (queryDocumentSnapshots != null) {
String dated;
for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {
//now here you have the list as you wanted but it is not sorted
//simply sort the list using something like this
//here receive the data in POJO class
// assuming you have saved your chat data in chatList
Collections.sort(chatList, (item1, item2) -> {
int firstChat = item1.chatDateSent() ? 0 : 1;
int secondChat = item2.chatDateSent() ? 0 : 1;
return first - second; // Ascending
}); // using JAVA 1_8
//now your list is sorted ASC, notifyDataSetChanged();
}
}
}
});
如果您需要更多帮助,请告诉我
希望这会有所帮助!
推荐阅读
- python - 将列表转换为 pandas 数据框中的 numpy 数组
- libgit2sharp - LibGit2Sharp - 在主分支中合并开发
- r - jupyter notebook 格式化 anova 与 summary.lm R
- ruby-on-rails - 了解 Railties 依赖项 - 捆绑程序“找不到兼容”
- uwp - 前台进程在启动时挂起,等待访问被防火墙阻止的 IP 地址
- javascript - 使用if条件jQuery滚动到orientationchange上的元素
- neo4j - 删除图中的所有索引
- azure-active-directory - 将 azure 函数连接到 b2c
- node.js - 带有节点休息 API 的 Amazon S3
- java - 方法内的重载构造函数InnerClass