异常:android.content.Context.getPackageName()' on a null object reference

代码:改方法是写在一个Fragment中

//onFalide方法是网络请求失败回调 
 @Override
            public void onFailed(int what, int responseCode, String errorMsg) {
                super.onFailed(what, responseCode, errorMsg);
                ...........
                if (responseCode == 1) {
               //延迟跳转到新的页面
                    ExThread.getInstance().executeByUIDelay(() -> {
                        Intent intent = new Intent(getContext(), CartActivity.class);
                        startActivity(intent);
                    }, 1000);
                }
            }

我们看下系统源码:

/**
     * Return the {@link Context} this fragment is currently associated with.
     */
    public Context getContext() {
        return mHost == null ? null : mHost.getContext();
    }

    /**
     * Return the {@link FragmentActivity} this fragment is currently associated with.
     * May return {@code null} if the fragment is associated with a {@link Context}
     * instead.
     */
    final public FragmentActivity getActivity() {
        return mHost == null ? null : (FragmentActivity) mHost.getActivity();
    }
// Host this fragment is attached to.
FragmentHostCallback mHost;  有可能为null  这个类我们可以认为他是用来管理Fragment生命周期,如果需要了解更多,自行百度学习。

原因:最常见是在 回调接口, 如网络请求回调,第三方登录回调 返回的时候 调用 context.startActivity 时 context 为空导致

解决方法:可以在 context 为空的时候使用 Application Context, 加上

if (!(context instanceof Activity)) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); }

 

 

更多推荐

'java.lang.String android.content.Context.getPackageName()' on a null