NullPointerException onActivityCreated / onStart / onViewCreated方法内的getView()警告 [英] NullPointerException Warning on getView() inside onActivityCreated/onStart/onViewCreated method

查看:480
本文介绍了NullPointerException onActivityCreated / onStart / onViewCreated方法内的getView()警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 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

确保对象真的永远不会为null,但是。

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.

这篇关于NullPointerException onActivityCreated / onStart / onViewCreated方法内的getView()警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆