gpt4 book ai didi

java - onActivityCreated/onStart/onViewCreated 方法中的 getView() 出现 NullPointerException 警告

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:02:02 27 4
gpt4 key购买 nike

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

我正在使用 fragment 。

代码:

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 之类的注解来抑制此类情况下的警告,因为这些方法使用的对象永远不会为 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

不过,请确保对象真的永远不会为 null。

可以找到有关 IntelliJ 的 @NotNull 和 @Nullable 注释的更多信息 here ,以及更多关于检查和压制的信息 here .

关于java - onActivityCreated/onStart/onViewCreated 方法中的 getView() 出现 NullPointerException 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30113709/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com