Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toast coming Multiple Times

Tags:

android

toast

In my application , on a button click I am creating a Toast as -

Toast.makeText(context,"Please Enter Username",Toast.LENGTH_SHORT).show();

But when someone clicks on the button 5-6 times and closes the application, or goes on another screen, it still keeps on showing the Toast for sometime on another screen also. I have seen many solutions for the same.

I have tried -

toast = Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT);
        toast.show();

and have cancelled this toast-

onPause(){

if(toast!=null){
toast.cancel();

}

and same on onDestroy()

I want that when anyone clicks on the button 5-6 times and goes out of the app or that activity, the toast message should disappear. Or suggest any alternate to solve the same.

like image 449
Gaurav Arora Avatar asked Dec 04 '22 12:12

Gaurav Arora


1 Answers

But it gives me a force close as - Toast was never called by using Toast.makeText();

You can make a field variable and method to only display one Toast at a time:

Toast toast;

public void displayToast(String message) {
    if(toast != null)
        toast.cancel();
    toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
    toast.show();
}

And in onPause() cancel any existing Toast when you exit:

protected void onPause() {
    if(toast != null)
        toast.cancel();
    super.onPause();
}

Now whenever you want to display a Toast, simply call:

displayToast("Please Enter Username");
like image 173
Sam Avatar answered Dec 28 '22 06:12

Sam