【问题标题】:KOTLIN : android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its viewsKOTLIN:android.view.ViewRootImpl$CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触摸其视图
【发布时间】:2020-03-13 02:54:37
【问题描述】:

我有这个代码:

    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),但它不起作用。

【问题讨论】:

  • 你需要使用Dispatchers.Main
  • 试过了,得到这个:android.os.NetworkOnMainThreadException

标签: android kotlin android-view kotlin-coroutines


【解决方案1】:

如果我没记错协程,那么以下应该可以工作:

lifecycleScope.launch { // runs on Main by default
    val specialMessage = withContext(Dispatchers.IO) {
        URL("https://finepointmobile.com/api/inventory/v1/message").readText()
    } 
    lastSavedProduct.text = specialMessage
}

【讨论】:

    【解决方案2】:

    试试这个

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

    然后在你的代码中使用它

    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
    }
    

    【讨论】:

    • 为什么需要惰性引用而不是直接使用 Dispatchers.Main?
    猜你喜欢
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    相关资源
    最近更新 更多