Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an array from Firestore?

I have the data structure illustrated below 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.

enter image description here

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]}

like image 889
Simon Ho Avatar asked May 08 '18 12:05

Simon Ho


People also ask

Can firestore store arrays?

Firestore lets you write a variety of data types inside a document, including strings, booleans, numbers, dates, null, and nested arrays and objects. Firestore always stores numbers as doubles, regardless of what type of number you use in your code.


1 Answers

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
like image 154
Doug Stevenson Avatar answered Sep 17 '22 15:09

Doug Stevenson