gpt4 book ai didi

android - 我的协程出现 "Cannot access database on the main thread since it may potentially lock the UI for a long period of time."错误

转载 作者:行者123 更新时间:2023-11-29 14:34:33 24 4
gpt4 key购买 nike

我的协程在主线程上运行,我在协程上下文中指定了它:

class ClickPreference(context: Context, attrs: AttributeSet) : Preference(context, attrs), CoroutineScope, View.OnClickListener {

override val coroutineContext: CoroutineContext
get() = Dispatchers.Main

override fun onClick(v: View?) {
when (key){
"logout" -> {
CoroutineScope(coroutineContext).launch {
CustomApplication.database?.clearAllTables()
Log.d("MapFragment", "Cleared Tables")
}
if (Profile.getCurrentProfile() != null) LoginManager.getInstance().logOut()
FirebaseAuth.getInstance().signOut()
val intent = Intent(context, MainActivity::class.java)
context.startActivity(intent)
}
}
}

但我仍然收到此错误:

java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.

在我上面的协程调用 CustomApplication.database?.clearAllTables() 到我的 Room 数据库。

这是我的CustomApplication:

class CustomApplication : Application() {

companion object {
var database: AppDatabase? = null
}

override fun onCreate() {
super.onCreate()
CustomApplication.database = Room.databaseBuilder(this, AppDatabase::class.java, "AppDatabase").build()
}

如果我的协程上下文在主线程上运行,为什么我仍然会收到错误?

最佳答案

错误表明它不应该在主线程上运行。数据库操作(以及所有其他形式的 IO)可能需要很长时间,应该在后台运行。

您应该使用专为运行 IO 操作而设计的 Dispatchers.IO

关于android - 我的协程出现 "Cannot access database on the main thread since it may potentially lock the UI for a long period of time."错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57657741/

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