在 onActivityCreated/onStart/onViewCreated 方法中 getView() 上的 NullPointerException 警告 [英] NullPointerException Warning on getView() inside onActivityCreated/onStart/onViewCreated method
问题描述
我知道 getView()
可能会在 onCreateView()
方法中返回 null,但即使我将下面的代码放入 onActivityCreated()
、onStart()
或 onViewCreated()
方法,它仍然显示有关 Android Studio 中可能的 NullPointerException
的警告(尽管我的程序在没有任何问题).如何摆脱这个警告?
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?
我正在使用片段.
代码:
datpurchased = (EditText) getView().findViewById(R.id.datepurchased);
//datpurchased defined as instance variable in the class
警告:
方法调用'getView().findViewById(R.id.datepurchased)'可能产生'java.lang.NullPointerException'
Method invocation 'getView().findViewById(R.id.datepurchased)' may produce 'java.lang.NullPointerException'
推荐答案
Android Studio 基于 IntelliJ IDEA,这是 IntelliJ 的一个特性,当您不检查由方法在使用前为null
.
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.
避免这种情况的一种方法是采用始终检查 null
或捕获 NullPointerException
风格的程序,但它会变得非常冗长,尤其是对于您知道总是会发生的事情返回一个对象并且永远不会null
.
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
.
另一种替代方法是使用诸如 @SuppressWarnings
之类的注释来抑制这种情况下的警告,用于使用您知道永远不能为空的对象的方法:
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.
可以在此处找到有关 IntelliJ 的 @NotNull 和 @Nullable 注释的更多信息,以及更多关于检查和抑制检查的信息这里.
More information on IntelliJ's @NotNull and @Nullable annotations can be found here, and more about inspections and supressing them here.
这篇关于在 onActivityCreated/onStart/onViewCreated 方法中 getView() 上的 NullPointerException 警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!