在firestore android上获取多个文档以及查询

时间:2020-09-14 18:05:56

标签: java android firebase google-cloud-firestore

我想检索多个文档并查看它,但是问题是它只检索一个文档。

CollectionReference collectionReference = db.collection("users");

collectionReference
    .whereArrayContains("zip",zip)
    .get()
    .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
            for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {

                String documentId = documentSnapshot.getId();
                String arrival = documentSnapshot.getString("arrival");
                String duration = documentSnapshot.getString("duration");
                String date = documentSnapshot.getString("date");
                Map distance = (Map)documentSnapshot.get("distance");
                ArrayList route = (ArrayList) documentSnapshot.get("route");

                String viewData = documentId + "\n" + arrival + "\n" + duration
                    + "\n" + date + "\n" + distance.toString();

                textView.setText(viewData);
            }
        }
    });

1 个答案:

答案 0 :(得分:0)

您可以通过查询集合中的文档来通过一个请求检索多个文档。您可以使用where()查询满足特定条件的所有文档,然后使用get()检索结果:

db.collection("cities")
        .whereEqualTo("capital", true)
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        Log.d(TAG, document.getId() + " => " + document.getData());
                    }
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });

您可以在“ Get multiple documents from a collection”文档中找到上述示例。