Search code examples
androidtoastonpause

Android Expanding Toast cause crash


Hey I am getting an crash on the code below. I am trying to expand a Toast for a certan amount of time, and "kill" the Toast when the onPause is runned. What am I doing wrong? The crash occures when i add timer.cancel() in the onPause

private boolean checkInternetConnection() {



    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    // test for connection
    if (cm.getActiveNetworkInfo() != null
            && cm.getActiveNetworkInfo().isAvailable()
            && cm.getActiveNetworkInfo().isConnected()) {

        splashTread.start();
        return true;
    } else {



        timer = new CountDownTimer(20000, 1000)
        {

            public void onTick(long millisUntilFinished) {toast.show();}
            public void onFinish() {toast.cancel();}

        }.start();



        return false;
    }
}



@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    finish();
timer.cancel():
}



@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    finish();
    timer.cancel():



}

}


Solution

  • Here is what you can do. The app crashes because the timer = null. The timer has never been run or set.

    Add this in both onDestroy and onPause:

    if (timer != null) {
            timer.cancel();
    
        }