NullPointerException在invalidateOptionsMenu上,即使检查为null

时间:2020-09-02 16:11:49

标签: android

在Logcat中,我看到了一个非常有趣的NullPointerException:

08-30 08:20:59.596 16965 16965 E AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.Activity.invalidateOptionsMenu()' on a null object reference
08-30 08:20:59.596 16965 16965 E AndroidRuntime:    at de.widmer.offerings.fragments.SongbookFragment.toggleMenuAndProgressBarVisibility(Unknown Source:17)
08-30 08:20:59.596 16965 16965 E AndroidRuntime:    at de.widmer.offerings.fragments.SongbookFragment.r0(Unknown Source:0)
08-30 08:20:59.596 16965 16965 E AndroidRuntime:    at de.widmer.offerings.fragments.SongbookFragment$2.onCompleted(Unknown Source:15)
08-30 08:20:59.596 16965 16965 E AndroidRuntime:    at com.tonyodev.fetch2.fetch.ListenerCoordinator$mainListener$1$onCompleted$$inlined$synchronized$lambda$2.run(Unknown Source:4)
08-30 08:20:59.596 16965 16965 E AndroidRuntime:    at android.os.Handler.handleCallback(Handler.java:883)
08-30 08:20:59.596 16965 16965 E AndroidRuntime:    at android.os.Handler.dispatchMessage(Handler.java:100)
08-30 08:20:59.596 16965 16965 E AndroidRuntime:    at android.os.Looper.loop(Looper.java:359)
08-30 08:20:59.596 16965 16965 E AndroidRuntime:    at android.app.ActivityThread.main(ActivityThread.java:7418)
08-30 08:20:59.596 16965 16965 E AndroidRuntime:    at java.lang.reflect.Method.invoke(Native Method)
08-30 08:20:59.596 16965 16965 E AndroidRuntime:    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
08-30 08:20:59.596 16965 16965 E AndroidRuntime:    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)

有趣的是,这是真实设备的Logcat中的第一个条目。

toggleMenuAndProgressBarVisibility的代码是:

private void toggleMenuAndProgressBarVisibility(boolean enabled) {
    mProgressbarHorizontalLayout.setVisibility(enabled ? View.GONE : View.VISIBLE);
    mUpdateOptionsEnabled = enabled;
    if (mContext != null && mContext instanceof Activity) {
        ((Activity)mContext).invalidateOptionsMenu();
    }
}

可以看出,在调用Context之前,我正在检查invalidateOptionsMenu是否为null以及实例Activity。 NullPointerException在这里怎么可能?

0 个答案:

没有答案