使用片段中的按钮进入另一个活动

时间:2018-12-06 09:36:02

标签: android android-fragments

Intent intent =new Intent(getActivity(),LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK );
startActivity(intent);

//这是我收到的错误//

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.salart.applogin, PID: 11946
    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:130)
        at android.content.Intent.<init>(Intent.java:6347)
        at com.example.salart.applogin.OneFragment$2.onAuthStateChanged(OneFragment.java:78)
        at com.google.firebase.auth.zzl.run(Unknown Source:3)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at com.google.android.gms.internal.firebase_auth.zzf.dispatchMessage(Unknown Source:6)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6944)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

2 个答案:

答案 0 :(得分:0)

从对片段有用的适配器调用

holder.demoView.setOnClickListener(v -> { Intent intent = new Intent();
                    /*Gson gson = new Gson();
                    Type type = new TypeToken<List<SampleModel>>(){}.getType();
                    String data = gson.toJson(parsable, type);
                    intent.putExtra("chat_data", data);*/ 
//ignore the commented above code, else if only you want something like this to parse data to the called activity.

      intent.setClass(v.getContext(), CallingActivity.class);
                        v.getContext().startActivity(intent);
 });

在片段内通过OnCreateView调用

    Intent intent =new Intent(getActivity(), CallingActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK );
                getActivity().startActivity(intent);

请注意v.getContext().startActivity(intent);,这让我从未失败!!!因此,如果您通过点击来调用活动,则只需使用view.getContext.startActivity(intent);

答案 1 :(得分:0)

尝试替换

startActivity(intent);

使用

getActivity().startActivity(intent);