android - 在 UI 线程错误室数据库 Android Studio 上运行
问题描述
我正在开发必须将 Room Database 中的数据显示到 Recycler-View 的 Android 应用程序。当我尝试加载数据时,它给了我这样的错误
Only the original thread that created a view hierarchy can touch its views.
就像我在默认线程中调用方法一样。
override fun getAllDatFromDatabase( appDatabase: AppDatabase) {
var list = listOf<TodoEntity>()
try {
GlobalScope.launch(Dispatchers.Default) {
list = appDatabase.TodoDao().getAll()
Log.d("hello","hello")
mView.showAllData(list)
}
}
catch (e:Exception){
Log.d("get hello",e.toString())
}
}
我正在使用 Kotlin 和
这是使用coroutineScope
解决方案
您不能从后台线程更新 ui,Dispatchers.Main
用于切换到主线程。
override fun getAllDatFromDatabase( appDatabase: AppDatabase) {
var list = listOf<TodoEntity>()
try {
GlobalScope.launch(Dispatchers.Default) {
list = appDatabase.TodoDao().getAll()
Log.d("hello","hello")
withContext(Dispatchers.Main){ //switch to main thread
mView.showAllData(list)
}
}
}
catch (e:Exception){
Log.d("get hello",e.toString())
}
}
推荐阅读
- ios - 在 AppleWatch 上记录用户在锻炼期间的路线
- azure - Azure DevOps 和逻辑应用 - 添加评论
- reactjs - Apollo UseMutation:TypeError:无法读取未定义的属性“数据”
- survival-analysis - ggsurvplot,错误(函数(...,row.names = NULL,check.rows = FALSE,check.names = TRUE,:
- sql - 更改 WPF 中现有 DataGridColumn 的日期格式
- php - Drupal 中的无效 CSRF 令牌获取私钥
- jestjs - 顺风复杂类(焦点等)和苗条项目中的笑话出错。仅在运行测试时
- asp.net - 授权属性与角色重定向到拒绝访问
- zip - 如何使用 EULA 创建 zip 文件?
- spring-boot - 安装 nginx 反向代理后 Spring Boot PUT 和 DELETE 请求返回 403