How can I get data from array data field from Cloud Firestore?

Arvind Kumar :

I am using Cloud Firestore and there is a array data in field. So how can I get data from array individually?

enter image description here

Alex Mamo :

To get the values within ip_range array, please use the following lines of code:

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());
                    }
                }
            }
        }
    }
});

Another approach would be:

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());
            }
        }
    }
});

In both cases, the output in your logcat will be:

[172.16.11.1, 172.16.11.2]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=91937&siteId=1