作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我必须通过对 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/
在我的设置中,我试图有一个界面 Table继承自 Map (因为它主要用作 map 的包装器)。两个类继承自 Table - 本地和全局。全局的将有一个可变的映射,而本地的将有一个只有本地条目的映射。
Rust Nomicon 有 an entire section on variance除了关于 Box 的这一小节,我或多或少地理解了这一点和 Vec在 T 上(共同)变体. Box and Vec
我是一名优秀的程序员,十分优秀!