1

all. I am facing a situation that is hardly understandable to me. I made a count-down timer, which is set to move to the next method when the value reaches 0. The problem is sometimes it shows negative numbers like -03:-15.

To be more specific to help you understand my timer, it does not always start from 1 minute because it reflects the current second. For example, if it is 17:00:20, it counts down from 40 to 0. When it is 17:00:35, it counts down from 25 to 0.

Count down timer code

fun getNowTimeSecond() : String {
    val now: Long = System.currentTimeMillis()
    val date = Date(now)
    val dateFormat = SimpleDateFormat("ss")
    return dateFormat.format(date)
}

private var mTimer = Timer()

private fun startTimer() {
  
    var remainTime = 60 - getNowTimeSecond().toInt()    
    mTimer = timer(period = 1000) {
        remainTime--
        _time.postValue("Time : " +
            (remainTime / 60.0).toInt().toString().padStart(2,'0') + ":" +
                    (remainTime % 60).toInt().toString().padStart(2,'0'))

        if(remainTime == 0) stopTimer()
      }
}

private fun stopTimer() {
    mTimer.cancel()
}
Lucy
  • 121
  • 12
  • 1
    This might help https://stackoverflow.com/questions/10032003/how-to-make-a-countdown-timer-in-android – Ammar Abdullah Jun 07 '22 at 08:18
  • Do you actually get `-03`? That would mean the `-` is added after the `padStart` that adds the leading zero, and by that point it's a `String` not a number. I can't see anything in this code that should create a negative number, but what's it meant to be doing? If you're counting down the remaining seconds in a minute, `remainTime / 60.0` should always be zero, and `(remainTime % 60).toInt()` is just `remainTime`. It looks like the code is meant for handling seconds and milliseconds, and I can't see how the first digits would be anything but `00` – cactustictacs Jun 07 '22 at 19:03
  • @cactustictacs I think it gives the negative number due to this line, ` var remainTime = 60 - getNowTimeSecond().toInt()` . Maybe it's called multiple times and the new ` getNowTimeSecond` is bigger than 60. – Lucy Jun 08 '22 at 00:17

1 Answers1

1

I think the problem might be that startTimer() could be called multiple times. mTimer will be overwritten with a new timer. And the old timer will keep running forever, because even if the old timer reaches 0 that old timer will then cancel the new timer by calling stopTimer(). A solution might be to call mTimer.cancel() (or stopTimer()) at the start of startTimer()

Ivo
  • 18,659
  • 2
  • 23
  • 35
  • My new question is how I can deliberately call it multiple times cos I want to test your solution. – Lucy Jun 08 '22 at 00:22