android - KOTLIN:android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建 View 层次结构的原始线程才能触摸其 View

标签 android kotlin android-view kotlin-coroutines

我有以下代码:

    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/

相关文章:

java - 为什么我的 ListView 中的项目不可点击?

java - 表 Laws_Table 没有名为 Category_name 的列(代码 1 SQLITE_ERROR)

Android Studio 3 Kotlin 版本

Android:你能有一个默认状态颜色是透明的涟漪效果吗?

android - ListView 适配器中的图像

javascript - 使用 HTML JS 在 Android WebView 中打开相机?

android - kotlin中onItemClickListener的实现

java - 在 Recycler Adapter 中获取 Activity onDestroy()

java - 在非 UI 线程上实例化 View

android - 在android中自定义 ImageView 上绘制