[android] android.content.Context.getPackageName()' on a null object reference

I am working with Fragments which implements an interface.

public class SigninFragment extends Fragment implements SigninInterface 

The interface's method implementation in the fragment class is as follows.

@Override
public void afterSubmitClicked(String userId, Bundle bundle) {

    Log.d(TAG,"Calling time afterSubmitClicked called"+bundle);
    
    if(!userId.equals("-1")){
        //Logged in successfully
        //Move to MusicHome
        
        Intent mIntent = new Intent(getActivity(),MusicHome.class);
        mIntent.putExtra("SigninFragment.user_details", bundle);
        startActivity(mIntent);
        
    }else{
        //Logging in failed
        //show error dialog
    }
    
}

This method is called after exectuting a AsynchronousTask (which extends AsyncTask) class.

But I am getting crash. And the error message shows

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

Logcat

   02-14 16:37:04.648: E/AndroidRuntime(28177): Process: com.raaga.android, PID: 28177
02-14 16:37:04.648: E/AndroidRuntime(28177): java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
02-14 16:37:04.648: E/AndroidRuntime(28177):    at android.content.ComponentName.<init>(ComponentName.java:77)
02-14 16:37:04.648: E/AndroidRuntime(28177):    at android.content.Intent.<init>(Intent.java:3996)
02-14 16:37:04.648: E/AndroidRuntime(28177):    at com.raaga.fragments.SigninFragment.afterSubmitClicked(SigninFragment.java:152)
02-14 16:37:04.648: E/AndroidRuntime(28177):    at com.raaga.asynctask.SignInAsyncTask.onPostExecute(SignInAsyncTask.java:92)
02-14 16:37:04.648: E/AndroidRuntime(28177):    at com.raaga.asynctask.SignInAsyncTask.onPostExecute(SignInAsyncTask.java:1)
02-14 16:37:04.648: E/AndroidRuntime(28177):    at android.os.AsyncTask.finish(AsyncTask.java:632)
02-14 16:37:04.648: E/AndroidRuntime(28177):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
02-14 16:37:04.648: E/AndroidRuntime(28177):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
02-14 16:37:04.648: E/AndroidRuntime(28177):    at android.os.Handler.dispatchMessage(Handler.java:102)
02-14 16:37:04.648: E/AndroidRuntime(28177):    at android.os.Looper.loop(Looper.java:135)
02-14 16:37:04.648: E/AndroidRuntime(28177):    at android.app.ActivityThread.main(ActivityThread.java:5221)
02-14 16:37:04.648: E/AndroidRuntime(28177):    at java.lang.reflect.Method.invoke(Native Method)
02-14 16:37:04.648: E/AndroidRuntime(28177):    at java.lang.reflect.Method.invoke(Method.java:372)
02-14 16:37:04.648: E/AndroidRuntime(28177):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
02-14 16:37:04.648: E/AndroidRuntime(28177):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

This question is related to android android-fragments fragment

The answer is


For me the problem was that I was passing Activity to the constructor, not Context

public Adapter(Activity activity, List<MediaItem> items, boolean can) {
    mItems = items;
    canEdit = can;
    mActivity = activity;
}

and using this activity to getDefaultSharedPreferences(), so I changed the Activity to Context and I was still calling the Adapter constructor with MainActivity.this


Put fragment name before the activity

Intent mIntent = new Intent(SigninFragment.this.getActivity(),MusicHome.class);

The answers to this question helped me find my problem, but my source was different, so hopefully this can shed light on someone finding this page searching for answers to the 'random' context crash:

I had specified a SharedPreferences object, and tried to instantiate it at it's class-level declaration, like so:

public class MyFragment extends FragmentActivity {
    private SharedPreferences sharedPref =
        PreferenceManager.getDefaultSharedPreferences(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //...

Referencing this before the onCreate caused the "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference" error for me.

Instantiating the object inside the onCreate() solved my problem, like so:

public class MyFragment extends FragmentActivity {
    private SharedPreferences sharedPref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //...
        sharedPref = PreferenceManager.getDefaultSharedPreferences(this);

Hope that helps.


You can solve your problem easily and use your activity anywhere in the activity, just store activity like this:

public class MainActivity extends AppCompatActivity{
      Context context = this;

      protected void onCreate(Bundle savedInstanceState) {....}

      AnotherClass {
          Intent intent = new Intent(context, ExampleActivity.class);
          intent.putExtra("key", "value");
          startActivity(intent);
      }

}

Use can use in global

Context context;

and create a constructor and passing the context. LoginClass is name of the class

LoginClass(Context context)
{this.context=context;}

and also when we call the class then use getApplicationContext like LoginClass lclass = new LoginClass(getApplicationContext) thats it.


android API level 23.

Use

getContext()

instead of

getActivity()

getActivity() gives the parent Activity, a Context object

Here You can use

MyActivity.this

instead of

getActivity() / getApplicationContext()


My class is not extends to Activiti. I solved the problem this way.

class MyOnBindViewHolder : LogicViewAdapterModel.LogicAdapter {
          ...
 holder.title.setOnClickListener({v->
                v.context.startActivity(Intent(context,  HomeActivity::class.java))
            })
          ...
    }

  public MessageAdapter(Context context, List<Messages> mMessageList) {

    this.mContext = context;
    this.mMessageList = mMessageList;

  }

I had the same problem trying to show a Toast in a fragment.

After some debugging I found out that I was removing the fragment before calling:

Toast.makeText(getContext(), "text", Toast.LENGTH_SHORT).show();

Because the fragment had been removed, the context became null, causing the exception.

Simple solution: call the getContext() before removing the fragment.


You solve the issue with a try/ catch. This crash happens when user close the app before the start intent.

try
{
    Intent mIntent = new Intent(getActivity(),MusicHome.class);
    mIntent.putExtra("SigninFragment.user_details", bundle);
    startActivity(mIntent);
}
catch (Exception e) {
    e.printStackTrace();
}

In my case the error occurred inside a Fragment on this line:

Intent intent = new Intent(getActivity(), SecondaryActivity.class);

It happened when I double clicked on an item which triggered the code above so two SecondaryActivity.class activities were launched at the same time, one on top of the other. I closed the top SecondaryActivity.class activity by pressing back button which triggered a call to getActivity() in the SecondaryActivity.class which came to foreground. The call to getActivity() returned null. It's some kind of weird Android bug so it usually should not happen. You can block the clicks after the user clicked once.


You only need to do this:

Intent myIntent = new Intent(MainActivity.this, nextActivity.class);

Due to onAttach is deprecated in API23 and above... In my Fragment, I declare and set parentActivity before hand everytime when I go into Fragment. Most likely happen due to when we pressed back button caused the context to become null. Therefore below is my solution.

private Activity parentActivity;

public void onStart(){
        super.onStart();
        parentActivity = getActivity();
//...

}

In my case I had a onCLick method in a recyclerview adapter,Context context; at the beginning.

 holder.cTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, StoryActivity.class);
                    intent.putExtra("STORY", mComments.get(position));
                    context.startActivity(intent);
                }
            });

And i changed to get the context from the current view

 holder.cTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(v.getContext(), StoryActivity.class);
                    intent.putExtra("STORY", mComments.get(position));
                    v.getContext().startActivity(intent);
                }
            });

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-fragments

FragmentActivity to Fragment How to start Fragment from an Activity How to use data-binding with Fragment In android how to set navigation drawer header image and name programmatically in class file? Android Fragment onAttach() deprecated How to convert any Object to String? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments java.lang.IllegalStateException: Fragment not attached to Activity java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

Examples related to fragment

FragmentActivity to Fragment Handling back button in Android Navigation Component android.content.Context.getPackageName()' on a null object reference Cannot resolve method 'getSupportFragmentManager ( )' inside Fragment How to move from one fragment to another fragment on click of an ImageView in Android? Android - save/restore fragment state Intent from Fragment to Activity Get the Application Context In Fragment In Android? Add Items to ListView - Android Using onBackPressed() in Android Fragments