Using Kotlin Coroutines to update my TextView crashes it:

1.6k Views Asked by At

I am a big newbie when it comes to Kotlin programming. I have basic understanding of Threading.

Here's the thing: I am trying to update my TextView (inside a fragment) once every second after clicking a button. I set the button's onClick function to include 10 Coroutine's delay(1000) calls. But I always get this error :

CalledFromWrongThreadException: Only Main Thread is allowed to change View properties

Is there any way to update my UI's views without using Kotlin Coroutines ?

With my current code, the app crashes after 2 seconds of clicking the button. Here's my code (As you can see, it's pretty rubbish):

GlobalScope.launch {
      for (i in 1..10){
      pingCount += 1
      GlobalScope.launch(Dispatchers.IO) { firstNum.text = "$pingCount"}
      delay(1000)}
}
2

There are 2 best solutions below

0
On BEST ANSWER

You have to use the main thread to update the UI. Just change the dispatcher to main.

GlobalScope.launch {
    for (i in 1..10){
    pingCount += 1
    GlobalScope.launch(Dispatchers.Main) { 
        firstNum.text = "$pingCount"
    }
      delay(1000)}
}
0
On

Or it could be this way too. Being in the IO, and then posting on the view itself.

GlobalScope.launch {
      for (i in 1..10){
      pingCount += 1
      GlobalScope.launch(Dispatchers.IO) { 
            firstNum.post{firstNum.text = "$pingCount"}
      }
      delay(1000)}
}