以下是一个示例代码,展示了如何查询Firestore实时数据库中子集合的所有文档并以对象形式返回:
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference parentCollectionRef = db.collection("yourParentCollection");
DocumentReference parentDocRef = parentCollectionRef.document("yourParentDocument");
CollectionReference childCollectionRef = parentDocRef.collection("yourChildCollection");
childCollectionRef.addSnapshotListener(new EventListener() {
@Override
public void onEvent(@Nullable QuerySnapshot querySnapshot, @Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.e(TAG, "Listen failed: " + e);
return;
}
List yourObjects = new ArrayList<>();
for (DocumentSnapshot document : querySnapshot.getDocuments()) {
YourObject yourObject = document.toObject(YourObject.class);
yourObjects.add(yourObject);
}
// 在这里处理yourObjects列表
}
});
请注意,你需要将代码中的 "yourParentCollection","yourParentDocument" 和 "yourChildCollection" 替换为你实际使用的集合和文档名称。
此外,你还需要创建一个类 "YourObject",它应该具有与Firestore文档中字段相匹配的属性。例如,如果你的Firestore文档具有名为 "name" 和 "age" 的字段,则可以创建如下的 "YourObject" 类:
public class YourObject {
private String name;
private int age;
// 构造函数,getter和setter方法等
// ...
}
这样,你就可以将Firestore文档转换为 "YourObject" 类的实例,并将其添加到 "yourObjects" 列表中。
请注意,上述代码使用了 addSnapshotListener 方法来实时监听子集合的更改。如果你只想查询一次子集合的所有文档,可以使用 get 方法而不是 addSnapshotListener 方法:
childCollectionRef.get().addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
List yourObjects = new ArrayList<>();
for (DocumentSnapshot document : task.getResult()) {
YourObject yourObject = document.toObject(YourObject.class);
yourObjects.add(yourObject);
}
// 在这里处理yourObjects列表
} else {
Log.e(TAG, "Error getting documents: " + task.getException());
}
}
});
这样,你将获得子集合的所有文档一次,并且不会实时监听更改。