-1

I am trying to get some values from a HashMap list. The list is multidimensional and it looks like:

{user_90= {
levels_win={level_2=true, level_1=true}, 
levels_stars={level_2=3, level_1=2}
}}

I get the list from firebase database using:

HashMap value = (HashMap) dataSnapshot.getValue();

How could I convert the HashMap in order to get the values using:

int star_level_2 = value["user_90"]["levels_stars"]["level_2"];
SNos
  • 3,430
  • 5
  • 42
  • 92

1 Answers1

0

Unfortunately for you (and fortunately for many others) Java is a statically strongly typed language so it will not work that way. Also (and I think this is unfortunate for almost everyone) you can't directly store primitive types such as int inside standard collections. And last, Java doesn't support operators overriding so you can't user "[" "]" to access values in a Map by key.

So what you can do is specify your types explicitly such as

HashMap<String, HashMap<String, HashMap<String, Object>>> container = (HashMap<>) dataSnapshot.getValue();
int star_level_2 = (Integer)(value.get("user_90").get("levels_stars").get("level_2"));

And if your data structure has different depth of inner objects, well you are out of luck with this approach and you'll have to cast result to specific data type after each get on each level.

SergGr
  • 23,570
  • 2
  • 30
  • 51
  • Thank you for your answer, thats what I thought intact after many hours trying I end it up casting the data for each value manually – SNos Mar 01 '17 at 18:08
  • @SNos, Some other answers on SO suggest that you might use Jackson ObjectMapper to simplify your code on write. See http://stackoverflow.com/questions/32848024/android-firebase-2-4-illegalstateexception-using-new-ref-updatechildren I haven't tried it myself but it might be that you can use the same approach to map objects back from Firebase. Note that you'll have to change your data structure to have keys with fixed names rather than indexed such as `user_90` – SergGr Mar 01 '17 at 18:17