【问题标题】:How can I get data from array data field from Cloud Firestore?如何从 Cloud Firestore 的数组数据字段中获取数据?
【发布时间】:2019-03-03 10:13:49
【问题描述】:

我正在使用 Cloud Firestore,并且字段中有一个数组数据。那么如何分别从数组中获取数据呢?

【问题讨论】:

  • 你想要整个数组吗?

标签: java android firebase google-cloud-firestore


【解决方案1】:

要获取ip_range数组中的值,请使用以下代码行:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
rootRef.collection("aic").document("ceo").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                Map<String, Object> map = document.getData();
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    if (entry.getKey().equals("ip_range")) {
                        Log.d("TAG", entry.getValue().toString());
                    }
                }
            }
        }
    }
});

另一种方法是:

rootRef.collection("products").document("06cRbnkO1yqyzOyKP570").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                ArrayList<String> list = (ArrayList<String>) document.get("ip_range");
                Log.d(TAG, list.toString());
            }
        }
    }
});

在这两种情况下,您的 logcat 中的输出将是:

[172.16.11.1, 172.16.11.2]

【讨论】:

  • 感谢@Alex Mamo。这是工作。但是你是怎么知道集合和文档名称的,但是我已经把它包装在图像中了。
  • 很高兴听到它成功了!因为this,我知道集合和文档名称:)
  • 上面的第二个解决方案,我收到警告“未经检查的演员:'java.lang.Object' to 'java.util.ArrayList'”
  • @LatiefAnwar 你可以使用注解来抑制它。
猜你喜欢
  • 2020-03-29
  • 2020-07-07
  • 1970-01-01
  • 2020-03-17
  • 1970-01-01
  • 1970-01-01
  • 2019-02-01
相关资源
最近更新 更多