onActivityCreated/onStart/onViewCreated 方法中 getView() 的 NullPointerException 警告

NullPointerException Warning on getView() inside onActivityCreated/onStart/onViewCreated method

我知道 getView() 可能 return 在 onCreateView() 方法中为 null,但即使我将下面的代码放在 onActivityCreated()onStart()onViewCreated() 方法,它仍然显示有关 Android Studio 中可能的 NullPointerException 的警告(尽管我的程序运行没有任何问题)。如何摆脱这个警告?

我正在使用 Fragments。

代码:

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 的一项功能,当您不检查对象 return 是否由方法 return 时,它会在编译时向您发出警告=12=] 使用前。

避免这种情况的一种方法是始终检查 null 或捕获 NullPointerException 风格的程序,但它可能会变得非常冗长,尤其是对于您知道总是 return 一个对象,永远不会 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, and more about inspections and supressing them here