I'm making an android app for learning to read and write in spanish. I am trying to get a map of arrays from firestore. There, I have a document with a field called "levels" that contains the map. Like this:
levels: { 1: "papa", "mama", 2: "mapa", 3: "cama","casa" }
see firebase data structure here
I'm getting the map this way:
HashMap <String, String[]> levelsMap = new HashMap<String, String[]>();
levelsMap = (HashMap<String, String[]>) documentSnapshot.get("levels");
So far, when debugging, the map has been correctly gotten and put in the levelsMap variable.
The debugger shows it like this:
levelsMap={HashMap@13651} size:3
"1" -> {ArrayList@13656} size = 2
key = "1"
value = {ArrayList@13656} size = 2
0 = "papa"
1 = "mama"
"2" -> {ArrayList@13673} size = 1
key = "2"
value = {ArrayList@13673} size = 1
0 = "mapa"
"3" -> {ArrayList@13675} size = 1
key = "3"
value = {ArrayList@13675} size = 1
0 = "cama"
Then, when I try to get an array out from the levelsMap, as the debugger says it's an arrayList I try to get it with the following line
List<String> levels = levelsMap.get("1");
but android studio points an error. It says that the variable "levels" expects a List but it is getting an Array. So then I try the following (as android studio suggests)
String[] level1 = levelsMap.get("1");
This time android studio points no error, but the app crashes at that line. the error in the console says:
java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.String[]
So, neither of those lines seem to work. Then, how can I get the level array?
List<Map<String, Object>> levels = (List<Map<String, Object>>) doccumentSnapshot.get("levels");
List<String> name = Arrays.asList(levels.get("1"));
Finally: I solved it with these lines:
levelsMap = new HashMap<String, List<String>>();
levelsMap = (HashMap<String, List<String>>) documentSnapshot.get("levels");
then, to get a whole level array:
List<String> level1 = levelsmap.get("1");
result: level1 = {0:papa, 1:mama}
then, to get a single word:
String word = levelsmap.get("1").get(0);
result: word = papa
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.