我有以下代码:
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
}
但是执行时出现以下错误:
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)
我尝试将
lifecycleScope.launch(Dispatchers.IO)
更改为lifecycleScope.launch(Dispatchers.Default)
,但不起作用。
最佳答案
如果我正确记得协程,那么以下方法应该起作用:
lifecycleScope.launch { // runs on Main by default
val specialMessage = withContext(Dispatchers.IO) {
URL("https://finepointmobile.com/api/inventory/v1/message").readText()
}
lastSavedProduct.text = specialMessage
}
关于android - KOTLIN:android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建 View 层次结构的原始线程才能触摸其 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60652344/