加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – NullPointerException onActivityCreated / onStart / o

发布时间:2020-12-14 05:06:28 所属栏目:Java 来源:网络整理
导读:我知道getView()可能会在onCreateView()方法中返回null,但即使我将以下代码放在onActivityCreated(),onStart()或onViewCreated()方法中)中,仍然会显示关于 Android Studio中可能的NullPointerException的警告我的程序运行没有任何问题).如何摆脱这个警告?
我知道getView()可能会在onCreateView()方法中返回null,但即使我将以下代码放在onActivityCreated(),onStart()或onViewCreated()方法中)中,仍然会显示关于 Android Studio中可能的NullPointerException的警告我的程序运行没有任何问题).如何摆脱这个警告?

我使用片段.

码:

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

警告:

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

解决方法

Android Studio基于IntelliJ IDEA,这是IntelliJ的一个功能,当您在使用它之前不检查方法返回的对象是否为null时,会在编译时给出警告.

避免这种情况的一种方法是总是检查null或捕获NullPointerException的样式的程序,但是它可以变得非常冗长,特别是对于您知道的事情将始终返回一个对象,而不会为null.

另一个替代方法是使用@SuppressWarnings等注解方法来抑制这种情况下的警告,方法使用您知道的对象永远不能为空:

@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

确保对象真的永远不能为null.

有关IntelliJ的@NotNull和@Nullable注释的更多信息可以在here中找到,更多关于检查和抑制它们的内容here.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读