Search code examples
androidkotlintimerandroid-support-librarycountdowntimer

Count down timer showing negative number error android


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()
}

Solution

  • 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()