I know getView()
可能会在内部返回 nullonCreateView()
方法,但即使我把下面的代码放在里面onActivityCreated()
, onStart()
or onViewCreated()
方法,它仍然显示有关可能的警告NullPointerException
在Android Studio中(虽然我的程序运行没有任何问题)。如何摆脱这个警告?
我正在使用碎片。
Code:
datpurchased = (EditText) getView().findViewById(R.id.datepurchased);
//datpurchased defined as instance variable in the class
Warning:
方法调用“getView().findViewById(R.id.datepurchased)”可能
产生“java.lang.NullPointerException”
Android Studio 基于 IntelliJ IDEA,这是 IntelliJ 的一项功能,当您没有检查方法返回的对象是否为null
在使用它之前。
避免这种情况的一种方法是以始终检查null
或捕获NullPointerException
,但它可能会变得非常冗长,特别是对于您知道将始终返回对象但从不返回的事物null
.
另一种选择是使用注释来抑制此类情况的警告,例如@SuppressWarnings
对于使用您知道永远不能为 null 的对象的方法:
@SuppressWarnings({"NullableProblems"})
public Object myMethod(Object isNeverNull){
return isNeverNull.classMethod();
}
或者,在您的情况下,行级抑制:
//noinspection NullableProblems
datpurchased = (EditText) getView().findViewById(R.id.datepurchased); //datpurchased defined as instance variable in the class
但请确保对象确实永远不会为空。
有关 IntelliJ 的 @NotNull 和 @Nullable 注释的更多信息,请参阅here https://www.jetbrains.com/idea/documentation/howto.html,以及有关检查和抑制检查的更多信息here https://www.jetbrains.com/idea/help/suppressing-inspections.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)