如何分别从Firestore中读取收藏集

时间:2019-04-23 07:58:47

标签: java android google-cloud-firestore

我编写了一些代码来读取集合并写入logcat,但是我想分别读取它们并添加到字符串中以供以后使用。我在集合下具有名称,cityLONG,cityLAT,campaignStartDate,campaignEndDate等属性。

Logcat : 8sAtwKcm273R1io1Blre => {name=TEST_LOC, cityLONG=29.3054092, cityLAT=40.9301514, campaignStartDate=2019-04-30, campaignEndDate=2019-10-30}

public void readFirestore() {
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    db.collection("campaigns")
            .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());
                    }
                }
            });
}

name, cityLONG, cityLAT, campaignStartDate, campaignEndDate

1 个答案:

答案 0 :(得分:1)

您可以在文档上使用getString()来获取特定的字符串字段,或者对其他类型使用get()并自己进行投射。

您的代码如下:

FirebaseFirestore db = FirebaseFirestore.getInstance();
        db.collection("campaigns")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful() && task.getResult() != null) {
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                Log.d(TAG, document.getId() + " => " + document.getData());
                                String cityLONG = document.getString("cityLONG");
                                //and so on
                            }
                        } else {
                            Log.d(TAG, "Error getting documents: ", task.getException());
                        }
                    }
                });