我的协程不工作,即使我已经做了所有声明在Android指南。我的代码有什么问题?
Logcat
D/FATAL EXCEPTION LOGCAT: java.lang.IllegalStateException:无法在主线程上访问数据库,因为它可能会锁定UI很长一段时间。
D/FATAL EXCEPTION LOGCAT: java.lang.IllegalArgumentException: bound必须为正
第二个例外是我的Random(),我想,但不知道发生了什么。
HomeFragment.kt
viewModel.allWordAggregate.observe(this.viewLifecycleOwner) { items ->
items.let {
try {
val random = Random().nextInt(it.size)
val randomWordAggregate = it.elementAt(random)
_randomWordAggregate = randomWordAggregate
} catch (e: Exception) {
Log.d("FATAL EXCEPTION LOGCAT", e.toString())
}
}
}
WordViewModel.kt
val allWordAggregate: LiveData<List<WordAggregate>> =
wordDao.getWordsWithMeanings().asLiveData()
WordDao.kt
@Transaction
@Query("SELECT * FROM word")
fun getWordsWithMeanings(): Flow<List<WordAggregate>>
InWordDao.kt,删除@Transaction
并尝试
@Query("SELECT * FROM word")
suspend fun getWordsWithMeanings(): Flow<List<WordAggregate>>
对于Random,检查list是否为空
viewModel.allWordAggregate.observe(this.viewLifecycleOwner) { items ->
val list = List<String>()
if (items.isNotEmpty) {
val random = Random().nextInt(list.size)
val randomWordAggregate = list.elementAt(random)
_randomWordAggregate = randomWordAggregate
}
}