Android Studio: Unboxing of 'xxx' may produce 'java.lang.NullPointerException'

ChuckZHB picture ChuckZHB · Apr 11, 2018 · Viewed 14k times · Source

I'm following the Android book example:

//Get the drink from the intent
int drinkIdd = (Integer)getIntent().getExtras().get(EXTRA_DRINKID);
Drink drink = Drink.drinks[drinkIdd];

And this project could be ran in Android Studio but with a yellow warning on line:

int drinkIdd = (Integer)getIntent().getExtras().get(EXTRA_DRINKID);

with:

info: Unboxing of '(Integer)getIntent().getExtras().get(EXTRA_DRINKID)' may produce 'java.lang.NullPointerException'

From my understanding, get(EXTRA_DRINKID) return an Object, and (Integer) converts it to int type to meet with int drinkIdd.

  • Could you tell me what this info means exactly, your answer will be appreciated for a beginner.
  • And could I write upper line like this? Using ( ) to wrap getIntent().getExtras().get() as a whole one since it finally return an object, and then convert it to int.

    int drinkIdd = (Integer)(getIntent().getExtras().get(EXTRA_DRINKID));
    

Answer

ישו אוהב אותך picture ישו אוהב אותך · Apr 12, 2018

This is because when calling the following code:

getIntent().getExtras().get(EXTRA_DRINKID);

The returning object can be null.

When you casting the value with Integer, it will not complaining because you can cast null to Integer.

But when you call the following:

int drinkIdd = (Integer)getIntent().getExtras().get(EXTRA_DRINKID);

because when you unboxing, it will complaining because you can't unboxing a null value.

You better using getInt() instead of get() like this:

int drinkIdd = getIntent().getExtras().getInt(EXTRA_DRINKID);

So you don't get the warning anymore and make your code more robust.

I don't know what book you're reading but I think you need to change your book reference. It seems the book Author haven't grasp the basic concept of Java and Android API. So, you need to use another Android book for your learning process until the Author has finished his/her job ;)

Note:
Converting an object of a wrapper type (Integer) to its corresponding primitive (int) value is called unboxing. Read more at Autoboxing and Unboxing.