gpt4 book ai didi

android - 使用协程更新 UI 异步调用

转载 作者:太空狗 更新时间:2023-10-29 15:34:09 27 4
gpt4 key购买 nike

我必须通过对 Room 数据库的异步调用来更新 UI,但是当我这样做时我遇到了这个错误:android.view.ViewRootImpl$CalledFromWrongThreadException:只有创建 View 层次结构的原始线程可以触摸其观点。

//FavoritesPresenter.kt

GlobalScope.launch {
favoritesView.showFavorites(ProductProvider.getAllProducts() as ArrayList<Product>)
}

//ProductProvider.kt

fun getAllProducts() : MutableList<Product> {
return dao.getAllProducts()
}

//ProductDao.kt

@Query("SELECT * FROM product")
fun getAllProducts(): MutableList<Product>

我需要的是通过我的 ProductProvider 更新我的 UI,因为我需要一个可靠的解决方案用于我所有的实体。

最佳答案

您应该使用 IO 协程从 Room 获取数据,然后切换到 Main (UI) 协程来更新 View 。

尝试:

GlobalScope.launch(Dispatchers.IO) {
val products = ProductProvider.getAllProducts() as ArrayList<Product>
withContext(Dispatchers.Main) {
favoritesView.showFavorites(products)
}
}

确保安装了 Android Coroutine 库,以便 Main Dispatcher 正确识别 Android 主线程。

api "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1"

关于android - 使用协程更新 UI 异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54671817/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com