【问题标题】:Retrieve documents from firestore according to its position in the List根据其在列表中的位置从firestore中检索文档
【发布时间】:2020-10-07 00:25:12
【问题描述】:

我的 firestore 数据库中有两个集合,第一个是所有文档的列表 (BlockList),第二个是用户的。当用户在应用上的 Recyclerview 上发表书签时,将文档的 id 和时间戳发送到用户收藏下的子收藏(收藏夹)。

我从主集合 (BlockList) 中检索基于此 ID 的文档列表,但我想根据每个用户的时间戳排列它们,因此我尝试在将它们添加到 Arraylist 之前按时间戳对它们进行排序记录列表,我得到了正确的结果。但是 recyclerview 仍然按文档 ID 升序检索它们!

firebaseFirestore.collection("Users")
                .document(userId).collection("Favorites").orderBy("timestamp", Query.Direction.DESCENDING).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    List<String> list = new ArrayList<>();
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        list.add(document.getId());
                    }
                    Log.d(TAG, list.toString());

                    if (list.size() != 0){
                        blockReffav = firebaseFirestore.collection("BlockList")
                                .whereIn(FieldPath.documentId(), list);

                        blockReffav.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                            @Override
                            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                                if(task.isSuccessful()){
                                    onFirestoreTaskComplete.blockListDataAdded(task.getResult().toObjects(BlockListModel.class));
                                } else {
                                    onFirestoreTaskComplete.onError(task.getException());
                                }
                            }
                        });

                    }

                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });

【问题讨论】:

    标签: android firebase google-cloud-firestore


    【解决方案1】:

    鉴于您当前检索文档的方式:

    blockReffav = firebaseFirestore.collection("BlockList")
            .whereIn(FieldPath.documentId(), list);
    

    无法在此查询中指定列表中 ID 的顺序,因此您将按照文档 ID 的(默认)顺序获取它们。

    我看到两个选项:

    1. 一份一份地索取文件,以便您以正确的顺序获得它们。
    2. 重新排序应用程序代码中的文档以匹配列表中的顺序。

    我推荐后者,因为它可能更简单、更可靠。

    【讨论】:

    • 请问你能告诉我如何用代码做到这一点吗?谢谢
    猜你喜欢
    • 2021-07-15
    • 2019-04-26
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 2021-09-23
    • 2021-05-06
    相关资源
    最近更新 更多