abd*_*him 10 java android nullpointerexception android-studio getview
我知道getView()可能会在onCreateView()方法内部返回null ,但即使我将下面的代码放在里面onActivityCreated(),onStart()或者onViewCreated()方法,它仍然会NullPointerException在Android Studio中显示有关可能的警告(尽管我的程序运行没有任何问题).如何摆脱这种警告?
我正在使用碎片.
码:
datpurchased = (EditText) getView().findViewById(R.id.datepurchased);
//datpurchased defined as instance variable in the class
Run Code Online (Sandbox Code Playgroud)
警告:
方法调用'getView().findViewById(R.id.datepurchased)'可能会产生'java.lang.NullPointerException'
Aar*_*n D 13
Android Studio基于IntelliJ IDEA,这是IntelliJ的一项功能,当您null在使用方法之前未检查方法返回的对象时,它会在编译时提供警告.
避免这种情况的一种方法是总是检查null或捕获的样式的程序NullPointerException,但它可能变得非常冗长,特别是对于你知道将永远返回一个对象的东西null.
另一种方法是使用注释来抑制对此类情况的警告,例如@SuppressWarnings对于使用您知道永远不会为null的对象的方法:
@SuppressWarnings({"NullableProblems"})
public Object myMethod(Object isNeverNull){
return isNeverNull.classMethod();
}
Run Code Online (Sandbox Code Playgroud)
或者,在您的情况下,线级抑制:
//noinspection NullableProblems
datpurchased = (EditText) getView().findViewById(R.id.datepurchased); //datpurchased defined as instance variable in the class
Run Code Online (Sandbox Code Playgroud)
但请确保对象确实永远不会为null.
有关IntelliJ的@NotNull和@Nullable注释的更多信息可以在这里找到,更多关于检查和压制它们的信息.
| 归档时间: |
|
| 查看次数: |
5152 次 |
| 最近记录: |