Search code examples
androidtoast

toast.cancel() doesn't seem to work


I am trying to stop a toast message from appearing / stacking up while an instance is still shown on the screen. I press the "decrement button" and it is to reduce the quantity by 1, however if the quantity is equal to 1 a toast message appears. Now the problem is, each time I press the "decrement button" the toast messages keep stacking up. This is what I have tried and I am unsure of how to prevent the stacking up issue:

Toast toastMessage;    

...

public void decrementQty(View view) {
        if (quantity == 1) {
            if (toastMessage != null) {
                toastMessage.cancel();
            }
            toastMessage.makeText(this, "You must order at least 1", Toast.LENGTH_SHORT).show();
            return;
        }
        quantity -= 1;
        displayQuantity(quantity);
    }

Solution

  • Try to add else branch

    public void decrementQty(View view) {
            if (quantity == 1) {
                if (toastMessage != null) {
                    toastMessage.cancel();
                    toastMessage = null;
                } else {
                   toastMessage = Toast.makeText(this, "You must order at least 1", Toast.LENGTH_SHORT)
                   toastMessage.show();
                }
                return;
            }
            quantity -= 1;
            displayQuantity(quantity);
        }