首页 > 解决方案 > 从 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 中是不可能的。


我怎样才能做到这一点?我必须使用复合索引吗?
请帮忙。

标签: androidfirebasegoogle-cloud-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();
                            }
                        }
                    }
                });

如果您需要更多帮助,请告诉我

希望这会有所帮助!


推荐阅读