遍历子集合以获取字段 -​​ Firestore Android

Mal*_*yum 4 java android firebase google-cloud-firestore

每个Notification ID集合只包含一个文档,我想迭代所有集合ToseefShop1并获取相应的文档名称和字段数据。

数据模型:

在此处输入图片说明 子集合:

在此处输入图片说明 在此处输入图片说明 代码:

dbRef.collection("Shop Notifications")
        .document("ToseefShop1")
        .get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
    @Override
    public void onSuccess(QuerySnapshot querySnapshot) {
        // Dont know what to do
    }
});
Run Code Online (Sandbox Code Playgroud)

这不是一个重复的问题。另一个问题(有人建议重复)是关于 javascript 的,答案是针对 Node.js 的。没有答案被接受。事实上,我在 firestore Java 中找不到 getcollections() 方法。

Ale*_*amo 5

Firestore 无法查询文档以获取其下的子集合。为了获得您要求的文档名称和字段数据,首先您需要拥有子集合的名称,然后在引用中使用它们。如果您只有 2 个子集合,我建议您使用以下代码:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
Query firstQuery = rootRef
    .collection("Shop Notifications")
    .document("ToseefShop1")
    .collection("Notification ID:0");
Query secondQuery = rootRef
    .collection("Shop Notifications")
    .document("ToseefShop1")
    .collection("Notification ID:1");

Task firstTask = firstQuery.get();
Task secondTask = secondQuery.get();

Task combinedTask = Tasks.whenAllSuccess(firstTask, secondTask).addOnSuccessListener(new OnSuccessListener<List<Object>>() {
    @Override
    public void onSuccess(List<Object> list) {
         //Do what you need to do with your list
    }
});
Run Code Online (Sandbox Code Playgroud)