1

I have observed recently in Crashlytics logs that few of my users got such exception:

Caused by java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.os.Bundle.get(java.lang.String)' on a null object reference

I'm suprised why I got it. Let me give you more context. Basically, I have two cases:

1.) I want to start activity and pass few attributes:

Intent intent = new Intent(currentActivity, NotificationActivity.class);
intent.putExtra("data", "something");
startActivity(intent);

I'm retrieving it in that way: getIntent().getExtras().get("data") and I'm getting exception mentioned earlier. The thing is I'm getting it quite rarely, for 99% cases it works but sometimes exception is thrown.

2.) the second case is when I'm building PendingActivity which is used as contentIntent in my notification:

Intent intent = new Intent(context, NotificationActivity.class);
intent.putExtra("data", "something");

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

I'm retrieving it in that way: getIntent().getExtras().get("data")

and as in the first case, sometimes I'm getting NPE.

Could you help me with understanding why that exception could have been thrown? is it something related with Activity lifecycle? I do not understand why for most cases it works perfectly fine but sometimes I'm getting null pointer.

Thanks for all advices.

jrola
  • 298
  • 7
  • 21

2 Answers2

0

You can use getIntent().hasExtra("data") to check if there is data or not Also I recommend to use getIntent().getExtras().getString("data") to get the data

0

For checking against NullPointerExceptions you can use something like this in your OnCreate:

if(savedInstanceState == null){
        Bundle extras = getIntent().getExtras();
        if(extras == null){
            yourString = null;
            sout("no string value found");            }
        else{
            yourString = extras.getString("nameOfYourString");
        }
    }
else{
    yourString= (String) savedInstanceState.getSerializable("nameOfYourString");
}