Toast上的NullPointerException

问题描述 投票:0回答:3

这是我的代码:

 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;
                    }

这是Crashlytics的堆栈跟踪:

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)

代码在MainActivity中,其中包括一个无线电播放器。这是因为用户已经关闭了MainActivity,使上下文无效?我怎样才能防止崩溃?

android nullpointerexception toast
3个回答
1
投票

更改

Toast.makeText(MainActivity.this, "Streaming not available", Toast.LENGTH_SHORT).show();

对此

Toast.makeText(getApplicationContext(), "Streaming not available", Toast.LENGTH_SHORT).show();

1
投票

当期望回调或在活动被销毁后接收广播时,这是可能的。要处理它,首先通过isFinishing()类的Activity方法检查活动是否存在。

if(!isFinishing()){
        Toast.makeText(MainActivity.this, "Streaming not available", Toast.LENGTH_SHORT).show();
    }

1
投票

您可以检查活动是否存活并按如下方式显示吐司

if(!MainActivity.this.isFinishing()) {
                Toast.makeText(MainActivity.this, "Streaming not available", Toast.LENGTH_SHORT).show();
  }
© www.soinside.com 2019 - 2024. All rights reserved.