如何从Cloud Firestore的数组数据字段获取数据?

7
我正在使用Cloud Firestore,其中某个字段中包含一个数组数据。那么我如何逐个获取数组中的数据?
请参考以下截图: enter image description here

你需要整个数组吗? - Aaditya Brahmbhatt
1个回答

9
要获取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。它正在工作。但是你怎么知道集合和文档名称,尽管我已经将其包装在图像中。 - Arvind Kumar
很高兴听到它起作用了!我知道集合和文档名称是因为这个 :) - Alex Mamo
在上面的第二个解决方案中,我收到了警告:“未经检查的转换:'java.lang.Object' 到 'java.util.ArrayList<java.lang.String>'”。 - Latief Anwar
1
@LatiefAnwar 你可以使用注释来抑制它。 - Alex Mamo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接