【发布时间】:2019-12-30 15:14:47
【问题描述】:
我的协程在我的协程上下文中指定的主线程上运行:
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()
}
如果我的协程上下文在主线程上运行,为什么我仍然会收到错误消息?
【问题讨论】:
标签: android kotlin android-room kotlin-coroutines