简体   繁体   中英

How can I get a map value inside a array from Firestore?

在此处输入图像描述

I have the above data structure stored in Cloud Firestore. I want to save the fleets which is an array of maps with "id" and "name" stored in Firestore. I have difficulty in getting the data and stored as an array. I am just able to get a weird string but any method to store as a string array? Below is the code I used.

public void getFleets() {

    DocumentReference document = mDb
            .collection(FirestoreService.CLIENT_COLLECTION)
            .document(new SessionService(getApplicationContext()).getClientUID());

    document.get()
            .addOnCompleteListener(task -> {
                if (task.isSuccessful() && task.getResult() != null) {
                    DocumentSnapshot doc = task.getResult();
                    List<String> group = (List<String>) doc.get("fleets");
                    Log.i(TAG, "getFleets: " + group);

                } else
                    Log.d(TAG, "Error getting documents: ", task.getException());
            });
}

This is the array result:

[{name=Caminhão, id=1}, {name=Escavadeira, id=2}, {name=Carregadeira, id=3}, {name=Trator, id=4}]

As you said, your fleets field is an array of maps. What you're seeing in the debug output is exactly what I'd expect. Note the outer square brackets indicate a java List type object, and the inner curly braces indicate java Map type objects inside it. However, your generic type is wrong. Instead of List<String> , you should use List<Map<String, Object>> to account for the Map objects in the List.

If you want a List<String> instead, you're going to have to write some code to pull the desired string out of the Map and build a new List using that value. So, if you wanted the name property out of each map item, you could do something like this:

List<Map<String, Object>> groups = (List<Map<String, Object>>) doc.get("fleets");
ArrayList<String> names = new ArrayList<>();
for (Map<String, Object> group : groups) {
    String name = group.get("name");
    names.add(name);
}

Now you have a list of names from the maps in the list.

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