NullPointerException Warning on getView() inside onActivityCreated/onStart/onViewCreated method

时光毁灭记忆、已成空白 提交于 2019-12-06 19:54:48

问题


I know getView() might return null inside onCreateView() method, but even if I put the below code inside onActivityCreated(), onStart() or onViewCreated() methods, it still shows the warning about a possible NullPointerException in Android Studio (although my program runs without any issue). How to get rid of this warning?

I am using Fragments.

Code:

datpurchased = (EditText) getView().findViewById(R.id.datepurchased); 
//datpurchased defined as instance variable in the class

Warning:

Method invocation 'getView().findViewById(R.id.datepurchased)' may produce 'java.lang.NullPointerException'


回答1:


Android Studio is based on IntelliJ IDEA, and this is a feature of IntelliJ that gives you warnings at compile time when you are not checking if an object returned by a method is null before using it.

One way to avoid this is program in the style that always checks for null or catches NullPointerException, but it can get very verbose, especially for things you know will always return an object and never null.

Another alternative is to suppress the warnings on such cases using annotations such as @SuppressWarnings for methods that use objects you know can never be null:

@SuppressWarnings({"NullableProblems"})
public Object myMethod(Object isNeverNull){
    return isNeverNull.classMethod();
}

or, in your case, a line-level suppression:

//noinspection NullableProblems
datpurchased = (EditText) getView().findViewById(R.id.datepurchased); //datpurchased defined as instance variable in the class

Be sure that the objects really can never be null, though.

More information on IntelliJ's @NotNull and @Nullable annotations can be found here, and more about inspections and supressing them here.



来源:https://stackoverflow.com/questions/30113709/nullpointerexception-warning-on-getview-inside-onactivitycreated-onstart-onvie

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