Search code examples
androidkotlinkotlin-coroutinesandroid-threading

Using Kotlin Coroutines to update my TextView crashes it:


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

Solution

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