Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

380
Visualizações
How to code a counter which loops within an interval in Kotlin Android

I am trying to build a countdown view inside an Android App with Kotlin. The code that I currently have crashes the app while running.

PS: Integer timer should be altered later on the application as well.

var timer:  Int = 50  // Declared globally
private fun timer(){
        timer_text.text = timer.toString()    // Text view in UI

        while (timer > 1){
            Handler().postDelayed({
                timer--
                timer_text.text = timer.toString()   // Update the Text view in UI
            }, 1000)
        }
    }

Logcat

I/sandaru.projec: Thread[6,tid=11100,WaitingInMainSignalCatcherLoop,Thread*=0xb400007b3dcd9f50,peer=0x13280238,"Signal Catcher"]: reacting to signal 3
I/sandaru.projec: 
I/sandaru.projec: Wrote stack traces to tombstoned
D/EGL_emulation: app_time_stats: avg=5.51ms min=1.98ms max=10.47ms count=60
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Looks like there is an ANR, since you are executing the while loop on main thread, you can try with below code, doing this will suspend instead of blocking

var timer:  Int = 50  // Declared globally
private suspend fun timer(){
    withContext(Dispatchers.Main) {
        timer_text.text = timer.toString()    // Text view in UI

        while (timer > 1){               
            timer--
            timer_text.text = timer.toString()   // Update the Text view in UI
            delay(1000)
        }
    }
}

and you need to execute the code from inside a coroutine, for ex. in the activity/fragment you can execute like this

lifecycleScope.launch {
    timer()        
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda