Android从Fragment Crash开始活动

时间:2017-09-08 08:59:50

标签: android android-fragments android-intent nullpointerexception android-volley

我正在尝试使用此代码通过添加此代码从Fragment启动活动,但应用程序崩溃了

Intent i = new Intent(getActivity(), IsActive.class);
startActivity(i);
getActivity().finish();

这是我的错误日志:

FATAL EXCEPTION: main                                                                        Process: media.aer.influencer, PID: 16165
  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:4459)
  at media.aer.influencer.Activity.MarkAsActiveFragment$10.onResponse(MarkAsActiveFragment.java:396)
  at media.aer.influencer.Activity.MarkAsActiveFragment$10.onResponse(MarkAsActiveFragment.java:333)
  at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:67)
  at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
  at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
  at android.os.Handler.handleCallback(Handler.java:746)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:148)
  at android.app.ActivityThread.main(ActivityThread.java:5443)
  at java.lang.reflect.Method.invoke(Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

我做错了什么?

2 个答案:

答案 0 :(得分:0)

而不是getActivity()

使用YourActivityName.getActivity();

在两个地方

private HomeActivity csActivity;
csActivity = (HomeActivity) getActivity();

因此您可以使用csActivity代替getActivity()

答案 1 :(得分:0)

每当你处理片段时,你应该使用getContext()来获取Activity。

    Intent intent=new Intent(getContext(), IsActive.class);
    startActivity(intent);
    getActivity().finish();