I build an android app Countdown Timer using Kotlin. When I start the timer using Coroutines it throws an error as follows.
Need your help that:
Error Text:
java.lang.RuntimeException: Can't create handler inside thread Thread[DefaultDispatcher-worker-1,5,main] that has not called Looper.prepare()
Code:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnStartPause.setOnClickListener {
if (isRunning) {
pauseTimer()
} else {
val time = edtTxtTimer.text.toString().trim()
timeInMilliSeconds = time.toLong() * 60000L // 1m = 60,000ms
CoroutineScope(Dispatchers.Default).launch {
startTimer(timeInMilliSeconds)
}
}
}
}
////////////////////////////////////////////////////
////////////////////////////////////////////////////
private fun startTimer(time_in_milli_second: Long) {
countdown_timer = object : CountDownTimer(time_in_milli_second, 1000) {
override fun onTick(millisUntilFinished: Long) {
timeInMilliSeconds = millisUntilFinished
updateUI()
}
override fun onFinish() {
btnStartPause.text = "Start"
loadConfeti()
}
}
countdown_timer.start()
isRunning = true
btnStartPause.text = "Pause"
btnReset.visibility = View.GONE
}
There are two ways to implement CountDownTimer to resolve the above error:
First Way
Dispatcher
using the HandlerThread
Second Way
Kotlin Flows
Main Thread