Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName() on getActivity()

When I try to create an intent on my Fragment class to move my activity page HomeScreenActivity using,

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

I'm getting following error Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference on Fabric. I got this error on Galaxy S7 Edge with os version 7. While executing line Intent intent = new Intent(getActivity(), HomeScreenActivity.class); (Line number 338 on LoginFragment.java)

Here is the full log I got from on 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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try to use attach method

public Activity mActivity;

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    this.mActivity = activity;
}

And use like this

Intent intent = new Intent(mActivity, HomeScreenActivity.class);
startActivity(intent);
mActivity.finish();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...