1

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)}
}
a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
yuroyami
  • 814
  • 6
  • 24
  • You can use this in coroutine. this.Activity.RunOnUiThread(() => { textview.text="Hello"; }); – Asad khan Jan 25 '21 at 06:00
  • I am using Kotlin. What do you mean by "use this in coroutine" ? You mean under GlobalScope ? Also, I am using fragments. Does that matter in this situation? – yuroyami Jan 25 '21 at 06:04
  • GlobalScope.launch(Dispatchers.MAIN) { firstNum.text = "$pingCount"} do it on main thread – DeePanShu Jan 25 '21 at 06:21
  • android studio is just an IDE, which helps you to code your apps. unless you're asking about a feature of the IDE, please don't add the tag :) – a_local_nobody Jan 25 '21 at 06:26

2 Answers2

1

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)}
}
Ashique Bava
  • 2,486
  • 2
  • 9
  • 21
-2

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)}
}
rahat
  • 1,840
  • 11
  • 24