当我尝试在我的Fragment类上创建一个intent来移动我的活动页面 HomeScreenActivity ,
Intent intent = new Intent(getActivity(), HomeScreenActivity.class);
startActivity(intent);
getActivity().finish();
我在Fabric上收到关注错误Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
。我在 Galaxy S7 Edge 上使用os版本 7 时出现此错误。执行第Intent intent = new Intent(getActivity(), HomeScreenActivity.class);
行时(LoginFragment.java上的行号 338 )
以下是我在Fabric上获得的完整日志,
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ComponentName.<init>(ComponentName.java:128)
at android.content.Intent.<init>(Intent.java:5359)
at com.example.android.fragments.LoginFragment.handleValidateEmployeeResponse(LoginFragment.java:338)
at com.example.android.fragments.LoginFragment.access$100(LoginFragment.java:53)
at com.example.android.fragments.LoginFragment$3.onResponse(LoginFragment.java:249)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
答案 0 :(得分:1)
我做了类似的事,
点击 Activity
参考
MainActivity activity = (MainActivity) getActivity();
然后将对象传递到您想要的位置,例如
Intent intent = new Intent(activity , HomeScreenActivity.class);
activity.finish();
答案 1 :(得分:1)
尝试使用attach
方法
public Activity mActivity;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.mActivity = activity;
}
并像这样使用
Intent intent = new Intent(mActivity, HomeScreenActivity.class);
startActivity(intent);
mActivity.finish();