简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM