SNos SNos -4 years ago 80
Android Question

Android - get Values from 2d HashMap

I am trying to get some values from a

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
in order to get the values using:

int star_level_2 = value["user_90"]["levels_stars"]["level_2"];

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download