如何从文档快照中读取子集合

时间:2017-11-22 17:08:33

标签: android firebase google-cloud-firestore

我在一个集合中有两个文档, 每个文档都有一个对象,所以我想以不同的方式阅读它们。

data.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>(){   
    @Override
    public void onSuccess(DocumentSnapshot documentSnapshot) {
        if (!documentSnapshot.exists()){

        }
    }
});

1 个答案:

答案 0 :(得分:0)

下面的代码迭代读取每个文档

db.collection("anyCollection")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            QuerySnapshot querySnapshot = task.getResult();
                            List<DocumentSnapshot> documentSnapshots = querySnapshot.getDocuments();// add check for each type of document...

                            for(DocumentSnapshot snapshot: documentSnapshots){
                                HashMap<String,Object> map = new HashMap<>();
                                map = (HashMap<String, Object>) snapshot.getData();
                                ///https://stackoverflow.com/a/1066607/3496570
                                for (Map.Entry<String, Object> entry : map.entrySet()) {
                                    String key = entry.getKey();
                                    Object value = entry.getValue();
                                    // ...
                                }
                            }
                        } else {
                            Log.d(TAG, "Error getting documents: ", task.getException());
                        }
                    }
                });