简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM