7

I get for next code

final boolean isOnList = myList.get(l.Id); 

error message :

"Unboxing of myList.get(l.Id) may produce NullPointerException".

MyList is :

private Map<String, Boolean> myList = new HashMap<>();

and l is:

 ActivityHome.Lists l = myList.get(position);

I have tried all proposed solutions but still get this error. Any suggestion to fix it?

  • Hi Nick, the error message is pretty self explanatory, the way you have your code designed means 'myList.get(position);' can be null. you need to design your code better. Here is an answer for the question you asked https://stackoverflow.com/a/49788177/5517088 – Kevin May 22 '19 at 08:21
  • 1
    Can't use that solution because I don't have getInt, the only option is get. I see that moderators compare just titles and ignore the body question. I already mentioned that I tested all proposed solutions from here. So in my opinion is not a duplicated question. –  May 22 '19 at 10:09
  • it is an exact duplicate. your code has an error because it is possible for `myList.get(position);` to be null, exactly like the other question. you need to redesign your code so that it isn't possible to have a nullpointerException. – Kevin May 22 '19 at 10:15
  • 6
    I found another way: final boolean isOnList = Objects.requireNonNull(myList.get(l.Id)); And my code is designed to can't get a null; –  May 22 '19 at 10:58
  • 1
    ```Boolean isOnList = myList.get(l.Id); return isOnList != null ? isOnList : false;``` Since Map.getObject, returns an object, you have to check that object against null first. If it is not null, use its value otherwise return false. I believe from API 24, you can provide a default value as well. – Henk-Martijn Oct 14 '20 at 14:36

0 Answers0