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

早过忘川 提交于 2019-11-29 20:18:40

问题


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));
    

回答1:


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.



来源:https://stackoverflow.com/questions/49766208/android-studio-unboxing-of-xxx-may-produce-java-lang-nullpointerexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!