1

I'm using Kotlin. I have a loop that will continue going. But for some reason, I am unable to update the text view. Here is my simplified example.

var i = 0
while (!Thread.currentThread().isInterrupted) {
    setString(i.toString())
    i++
    Log.i("Loging value of i === ", i.toString())
}


private fun setString (string : String) {
    tempText.text = string
}
Ebad Saghar
  • 1,107
  • 2
  • 16
  • 41

3 Answers3

2

What happened is because you are calling the UI updating inside a different Thread other than the main/UI Thread, your code can't reach the Views on the UI Thread.

Call the code that updates something on the UI inside a runOnUiThread like https://stackoverflow.com/a/11140429/10464730 (just copy the runOnUiThread part).

Or do a .post on the TextView like this https://stackoverflow.com/a/9884344/10464730. Most of the time I use runOnUiThread first. If doesn't work, that's when I use .post.

Sorry the code I posted are Java but I think you could look up the equivalent of it on Kotlin.

rminaj
  • 560
  • 6
  • 28
  • I figured it out. Although setting the text must be done on the UIThread, so having a loop will block the UIThread. I used a Handler and Runnable instead of a loop and now it works. Thanks. – Ebad Saghar May 31 '19 at 22:18
  • AFAIK, `loop` doesn't block the UI `Thread`. I think `.post` is what you'll need inside `loop`s. Well, `Handler` and `Runnable` would work as well. Glad to have been of some help. – rminaj Jun 01 '19 at 05:43
1

I also like this coroutines approach to update a textview, please drop it in your onCreate, also include your gradle implementation for coroutines:

    GlobalScope.launch(Dispatchers.Main) {
        var i = 0
        while (i < 100) {
            textViewId.setText("#$i")
            i++
            delay(300)
        }
    }
Fausto Checa
  • 163
  • 13
0

View's can only be updated in UI Thread. try something like this :

while (!Thread.currentThread().isInterrupted) {

 runOnUiThread(
            object : Runnable {
                override fun run() {
                    //do your view update work here
                      setString(i.toString())
                }
            }
    )
    i++
}
Shiva Snape
  • 544
  • 5
  • 9