【问题标题】:How to get all documents in sub-collections to RecyclerView in Firebase Firestore如何将子集合中的所有文档获取到 Firebase Firestore 中的 RecyclerView
【发布时间】:2020-08-11 13:31:57
【问题描述】:

在我的 Firestore 数据库中,我有一个包含多个文档的“类别”集合,而这些文档又具有包含相应文档的“产品”子集合。

我正在尝试获取所有子集合中的所有文档并填充到 Recylerview 中,但我失败了。

这是我的代码;

 private void populateAllProducts() {
        Log.d(TAG, "populateAllProducts called: ");
          database
                .collection(Globals.CATEGORIES)
                .get()
                .addOnCompleteListener(task -> {
                    if (task.isSuccessful()) {
                            for (QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())) {
                                Category category = document.toObject(Category.class);
                                Log.d(TAG, "Category: " + category.getName());
                                    database
                                        .collection(Globals.CATEGORIES)
                                        .document(category.getUuid())
                                        .collection(Globals.PRODUCTS)
                                        .get()
                                        .addOnCompleteListener(task1 -> {
                                            if (task.isSuccessful()) {
                                                    for (QueryDocumentSnapshot snapshot : Objects.requireNonNull(task1.getResult())) {
                                                        Product product = snapshot.toObject(Product.class);
                                                        Log.d(TAG, "All products: " + product.getName());
                                                    }
                                                }
                                        })
                                        .addOnFailureListener(e -> Log.e(TAG, "Error: ", e));
                            }
                    }
                })
                .addOnFailureListener(e -> {
                    vars.verityApp.crashlytics.log("Error while fetching categories");
                    Log.e(TAG, "Error occured: ", e);
                    vars.verityApp.crashlytics.recordException(e);
                });
    }

但是我收到了这个致命异常;

2020-08-11 16:27:16.358 26161-26161/com.verityfoods E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.verityfoods, PID: 26161
    java.lang.NullPointerException: Provided document path must not be null.
        at com.google.firebase.firestore.util.Preconditions.checkNotNull(Preconditions.java:147)
        at com.google.firebase.firestore.CollectionReference.document(CollectionReference.java:103)
        at com.verityfoods.ui.bottomviews.shop.ShopFragment.lambda$populateCategories$2$ShopFragment(ShopFragment.java:87)
        at com.verityfoods.ui.bottomviews.shop.-$$Lambda$ShopFragment$dIuQdpUfodkE_zdMSo4L2Rr4DL0.onComplete(Unknown Source:2)
        at com.google.android.gms.tasks.zzj.run(Unknown Source:4)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

感谢您的帮助!

【问题讨论】:

    标签: java android firebase android-recyclerview google-cloud-firestore


    【解决方案1】:

    您收到以下错误:

    java.lang.NullPointerException:提供的文档路径不能为空。

    因为您在引用中传递了 null 值。 category.getUuid() 最有可能返回 null,因此会出现该错误。看到你的getUuid() getter,我可以猜测数据库中该属性的名称不是uuid,所以这很可能是原因。

    我正在尝试获取所有子集合中的所有文档并填充到 Recylerview 中

    要获取所有products 子集合中的所有数据,您应该使用Firestore collection group query 而不是常规CollectionReference 对象。在代码中,此查询应如下所示:

    db.collectionGroup("products").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                //Iterate to get the products out of the queryDocumentSnapshots object
            }
        });
    

    【讨论】:

    • 谢谢@Alex Mamo,让我试试第二个选项。我会回到这里查看结果。
    • 谢谢亚历克斯,这是有效的,我已经记录了结果,它有所有的文件,非常感谢。你救了我。
    • @DenisOluka 如果此答案解决了您的问题,您应该接受它(单击它旁边的复选标记)。这有两件事。它让每个人都知道您的问题已得到您满意的解决,并为帮助您的人提供帮助。 See here 以获得完整的解释。
    • 对不起,我没有立即这样做,但我马上就这样做了。
    • @AlexMano,在上述答案中,数据库可能会随着时间的推移而变得越来越大,这意味着向 recyclerview 查询太多数据会变慢。有没有办法在collectionGroup上使用FirestorePagingOptions
    【解决方案2】:

    您正在检查第一个任务是否在第二个任务中完成。

    private void populateAllProducts() {
            Log.d(TAG, "populateAllProducts called: ");
              database
                    .collection(Globals.CATEGORIES)
                    .get()
                    .addOnCompleteListener(task -> {
                        if (task.isSuccessful()) {
                                for (QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())) {
                                    Category category = document.toObject(Category.class);
                                    Log.d(TAG, "Category: " + category.getName());
                                        database
                                            .collection(Globals.CATEGORIES)
                                            .document(category.getUuid())
                                            .collection(Globals.PRODUCTS)
                                            .get()
                                            .addOnCompleteListener(task1 -> {
                                                if (task.isSuccessful()) { //Here should be task1, not task
                                                        for (QueryDocumentSnapshot snapshot : Objects.requireNonNull(task1.getResult())) {
                                                            Product product = snapshot.toObject(Product.class);
                                                            Log.d(TAG, "All products: " + product.getName());
                                                        }
                                                    }
                                            })
                                            .addOnFailureListener(e -> Log.e(TAG, "Error: ", e));
                                }
                        }
                    })
                    .addOnFailureListener(e -> {
                        vars.verityApp.crashlytics.log("Error while fetching categories");
                        Log.e(TAG, "Error occured: ", e);
                        vars.verityApp.crashlytics.recordException(e);
                    });
        }
    

    当代码到达时,可能 task1 尚未完成,因为任务实际上已完成,所以无论如何都会触发

    【讨论】:

      猜你喜欢
      • 2021-05-09
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      • 2019-06-08
      • 1970-01-01
      • 1970-01-01
      • 2021-01-23
      • 2018-04-03
      相关资源
      最近更新 更多