问题描述
我的协程正在主线程上运行,这是我在我的协程上下文中指定的:
My Coroutine is running on the main thread, which i've specified in my Coroutine context:
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)
}
}
}
但是我仍然收到此错误:
But I'm still getting this error:
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
数据库.
on my above Coroutine call CustomApplication.database?.clearAllTables()
to my Room
database.
这是我的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()
}
如果我的协程上下文在主线程上运行,为什么仍会出现错误?
Why am I still getting the error if my coroutine context runs on the main thread?
推荐答案
该错误表明该代码不应在主线程上运行.数据库操作(以及其他所有形式的IO)可能会花费很长时间,应该在后台运行.
The error says that it should NOT run on the main thread. Database operations (and every other form of IO) can take a long time and should be run in the background.
您应该使用专门用于运行IO操作的Dispatchers.IO
.
You should use Dispatchers.IO
which is designed for running IO operations.
这篇关于“无法访问主线程上的数据库,因为它可能会长时间锁定UI."我的协程错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!