【问题标题】:NullPointerException Warning on getView() inside onActivityCreated/onStart/onViewCreated method在 onActivityCreated/onStart/onViewCreated 方法内的 getView() 上出现 NullPointerException 警告
【发布时间】:2015-07-18 18:32:04
【问题描述】:

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

我正在使用片段。

代码:

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

警告:

方法调用 'getView().findViewById(R.id.datepurchased)' 可能 产生'java.lang.NullPointerException'

【问题讨论】:

    标签: java android android-studio nullpointerexception getview


    【解决方案1】:

    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
    

    不过,请确保对象永远不会为空。

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

    【讨论】:

    • 我可以使用noinspection ConstantConditions 取消我的警告。但是关于禁止检查的链接非常有用!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多