简体   繁体   中英

Android Hashmap returning null

I have an expandable listview where the data is stored in a

HashMap<Integer, List<MyChildObject>>

and when expanding it crashes saying List.size() null pointer in the adapter.getChildrenCount() where its simply:

public int getChildrenCount(int groupPosition) {
    return mMap.get(groupPosition).size();
}

Now I put a break point in a ran debugger and saw that my mMap was fine, I'm testing with one element where the list of that element contains one child object. I can see in debugger the element is in fact a list with size = 1.

But testing List<MyChildObject> list = mMap.get(0); it returns null even when I can see in debugger mMap has that element ( <Integer.valueOf(0), non null list of objects> ).

Whats even weirder is when testing with 4 hashmap elements:

<0, list>
<1, list>
<2, list>
<3, list>

It works fine and I'm able to access the non null list by calling mMap.get(n)...

Am I not using HashMap correctly here with integer keys? Why am I unable to retrieve any elements?

Odds are pretty good it's checking the Integer Object which boxes and unboxes correctly for values between -128 and 127, because typically these get saved. But, the equals between these should be the same for both given that the key value for integer does check the underlying value rather than the memory location.

Why are you using a hashmap? I mean doesn't this form call out for ArrayList<ArrayList<MyChildObject> > ? And in case, you should switch your count function to have a null check anyhow.

public int getChildrenCount(int groupPosition) {
    List<MyChildObject> list = mMap.get(groupPosition);
    if (list == null) return 0;
    return list.size();
}

Because odds are good if you allow in zero sized objects, you're just as good off using a null.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM