How to get an array from Firestore?

Simon Ho :

enter image description here

I have the above data structure stored in Cloud Firestore. I want to save the dungeon_group which is an array of strings 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.

I am able to achieve this in Swift as follow, but not sure how to do the same in Android.

//Swift

Firestore.firestore().collection("dungeon").document("room_en").getDocument { (document, error) in
        if let document = document {
            let group_array = document["dungeon_group"] as? Array ?? [""]
            print(group_array)
        }

    }

//JAVA Android

    FirebaseFirestore.getInstance().collection("dungeon").document("room_en").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                DocumentSnapshot document = task.getResult();
                String group_string= document.getData().toString();
                String[] group_array = ????

                Log.d("myTag", group_string);
            }
        });

Console OutPut as the follow:{dungeon_group=[3P, Urgent, Mission Challenge, Descended, Collaboration, Daily, Technical, Normal]}

Doug Stevenson :

When you call DocumentSnapshot.getData(), it returns a Map. You're just calling toString() on that map, which is going to give you a dump of all the data in the document, and that's not particularly helpful. You need to access the dungeon_group field by name:

DocumentSnapshot document = task.getResult();
List<String> group = (List<String>) document.get("dungeon_group");
  • edit: syntax error in typecasting

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=431749&siteId=1