问题描述
在我的Android应用中,我使用Room
作为本地数据库来存储用户的帐户信息。当我提出一个简单的Room
请求以检索存储在数据库中的Account
对象时,我收到以下错误消息:
java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
这是我从中发出本地数据库请求的Fragment
代码:
// AccountInformationFragment.kt
accountDataFragmentViewModel.retrieveAccountData(accountId).observe(viewLifecycleOwner,Observer {
// do some stuff
})
在ViewModel
类中,我实现了retrieveAccountData()
,如下所示:
// AccountInformationFragmentViewModel.kt
// used to get the account from the local datasource
fun retrieveAccountData(id:Long): LiveData<Account>{
val result = MutableLiveData<Account>()
viewModelScope.launch {
val account = authRepository.retrieveAccountData(id)
result.postValue(account)
}
return result
}
在Repository
类中,我已经实现了retrieveAccountData()
,如下所示:
// AccountRepository.kt
suspend fun retrieveAccountData(accId:Long): Account =
accountDao.retrieveAccountData(accId)
我知道我必须使用某种asnyc操作,因为在主线程上执行本地数据库操作可能会花费很长时间。
但是在ViewModel
类中,我在viewModelScope
内部启动了协程。这还不够吗?基于例外,似乎并非如此。因此,有人可以告诉我如何正确执行此操作。
编辑:
这是道课:
@Query("SELECT * FROM account_table WHERE id = :id")
fun retrieveAccountData(id: Long) : Account
预先感谢
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)