Pedro Gonzalez
Pedro Gonzalez

Reputation: 1459

NullPointerException on Toast

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

Answers (3)

Curio
Curio

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

Abilash
Abilash

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

SpiritCrusher
SpiritCrusher

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

Related Questions