Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get specific array value Cloud Firestore

I want to get the value of the second index inside a document of the Firestore database. Currently, I am able to get the entire array but I couldn't get a value by its index.

database image

This is the code I have which returns the entire value of the array .

        firebaseFirestore.collection("levels").document("data").get()
            .addOnCompleteListener(task -> {
                if (task.isSuccessful()) {
                    ArrayList arrayList = (ArrayList) task.getResult().get("images"); 
                    // Here i am getting the entire data from the document
                }
            });
like image 457
Nuwan Codezync Avatar asked Sep 19 '26 07:09

Nuwan Codezync


1 Answers

Currently, I am able to get the entire array.

That's the way Firestore works. All Cloud Firestore listeners fire on the document level. So there is no way you can get only some particular fields in a document. In your case, you cannot get only the "images" array that exists inside that document, or just a value from within that array. It's the entire document or nothing.

But I couldn't get a value by its index database image.

Since you already got the array, you can get the value that exists at the second index very simply. Knowing that the first index is 0, the second index would be 1. So you have to make the following request:

ArrayList arrayList = (ArrayList) task.getResult().get("images");
String secondImage = arrayList.get(1);
like image 126
Alex Mamo Avatar answered Sep 21 '26 21:09

Alex Mamo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!