1

I have this code:

    lifecycleScope.launch(Dispatchers.Default) {
        val specialMessage = URL("https://finepointmobile.com/api/inventory/v1/message").readText()
        d("Globby", "The message is: $specialMessage")
        lastSavedProduct.text = specialMessage                //line 41
    }

But when executing I get the following error:

ERROR : android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
        at com.example.MainActivity$onCreate$2.invokeSuspend(MainActivity.kt:41)

I tried changing lifecycleScope.launch(Dispatchers.IO) to lifecycleScope.launch(Dispatchers.Default) but it doesn't work.

ich5003
  • 838
  • 1
  • 9
  • 24
Globby
  • 51
  • 2
  • 8

2 Answers2

3

If I remember coroutines correctly, then the following should work:

lifecycleScope.launch { // runs on Main by default
    val specialMessage = withContext(Dispatchers.IO) {
        URL("https://finepointmobile.com/api/inventory/v1/message").readText()
    } 
    lastSavedProduct.text = specialMessage
}
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
0

Try this

// Make a CoroutineContext variable
val main: CoroutineContext by lazy { Dispatchers.Main }

then use it in your code

lifecycleScope.launch(main) {
    val specialMessage = URL("https://finepointmobile.com/api/inventory/v1/message").readText()
    d("Globby", "The message is: $specialMessage")
    lastSavedProduct.text = specialMessage //line 41
}
Erwin Kurniawan A
  • 958
  • 2
  • 9
  • 17