Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 334
Arvind Kumar Avatar asked Sep 27 '18 13:09

Arvind Kumar


1 Answers

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]
like image 143
Alex Mamo Avatar answered Sep 17 '22 13:09

Alex Mamo