androidcountdowntimerhourglass

Timer/hourglass wont stop


I tried the same thing with the timer but still not working

Everytime I try to start the timer , it works but when I try to click again the button and cancel the countdown, it is not stopping or cancelling.

Here is my code:

public void timer(final Button btnBooking) {

    Hourglass hourglass = new Hourglass(5000, 1000) {
        @Override public void onTimerTick(long timeRemaining) { // Update UI
            btnBooking.setText("CANCEL " + "(" + timeRemaining + ")");
        }

        @Override public void onTimerFinish() { // Timer finished
            if (isBooking) {
                btnBooking.setText("CANCEL");
            }
            listener.startBooking();
        }
    };

    if (!isBooking) {
        hourglass.startTimer();
        isBooking = true;
    } else {
        isBooking = false;
        hourglass.stopTimer();
        btnBooking.setText("BOOK");
    }

}

Solution

  • Try this, might help you.

    if (!isBooking) {
                hourglass = new Hourglass(5000, 1000) {
                    @Override
                    public void onTimerTick(long timeRemaining) { // Update UI
                        btnBooking.setText("CANCEL " + "(" + timeRemaining / 1000 + ")");
                    }
    
                    @Override
                    public void onTimerFinish() { // Timer finished
                        if (isBooking) {
                            btnBooking.setText("CANCEL");
                            listener.startBooking();
                        }
    
                    }
                };
                hourglass.startTimer();
                isBooking = true;
            } else {
                if (!hourglass.isRunning()) {
                    dialogUtils.askDialog("Are you sure you want to cancel?", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            listener.stopBooking();
                            isBooking = false;
                            hourglass.stopTimer();
                            btnBooking.setText("BOOK");
                        }
                    }, null);
                } else {
                    isBooking = false;
                    hourglass.stopTimer();
                    btnBooking.setText("BOOK");
                }
            }