首页 > 解决方案 > 在 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

标签: androidkotlinandroid-fragmentsandroid-roomkotlin-coroutines

解决方案


您不能从后台线程更新 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())
        }
    }

推荐阅读