Reputation: 1459
this is my code:
case PlaybackStateCompat.STATE_ERROR: {
mRadioProgress.setVisibility(View.GONE);
mPlayStopButton.setVisibility(View.VISIBLE);
mPlayStopButton.setImageResource(R.drawable.player_play);
Toast.makeText(MainActivity.this, "Streaming not available", Toast.LENGTH_SHORT).show();
break;
}
and this is Crashlytics stack trace:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke interface method 'void android.app.INotificationManager.enqueueToast(java.lang.String, android.app.ITransientNotification, int)' on a null object reference
at android.widget.Toast.show(Toast.java:286)
Code is in MainActivity, which includes a radio player.Is it because the user has already closed MainActivity, making the context invalid? How can I prevent the crash?
Upvotes: 0
Views: 1735
Reputation: 1371
Change
Toast.makeText(MainActivity.this, "Streaming not available", Toast.LENGTH_SHORT).show();
to this
Toast.makeText(getApplicationContext(), "Streaming not available", Toast.LENGTH_SHORT).show();
Upvotes: 1
Reputation: 343
You can check if the activity is alive and show toast as follows
if(!MainActivity.this.isFinishing()) {
Toast.makeText(MainActivity.this, "Streaming not available", Toast.LENGTH_SHORT).show();
}
Upvotes: 1
Reputation: 21053
This can be possible when expecting for callback or receive a broadcast after Activity is destroyed .To handle it check for activities existence first by isFinishing()
method of Activity
class.
if(!isFinishing()){
Toast.makeText(MainActivity.this, "Streaming not available", Toast.LENGTH_SHORT).show();
}
Upvotes: 1