如何解决使用自定义协程作用域访问数据库内容
目前,在遵循这些教程之后,我有一个使用Room数据库,LiveData,Databinding和ViewModels的应用程序:
https://codelabs.developers.google.com/codelabs/android-room-with-a-view-kotlin/
https://github.com/googlecodelabs/android-room-with-a-view/tree/kotlin
我现在通过添加通知来扩展我的应用程序。我的数据库充满了要通过通知显示给用户的内容。我想通过将数据库中的〜100个条目放入NotificationHandler类中,然后随机选择一个条目并将其显示给用户来实现。我正在努力使用DAO将数据库中的内容获取到NotificationHandler类中。
将数据库条目放入应用程序其他位置的ViewModel中时,将使用ViewModelScope,因此不需要复杂的协程或担心范围。在我的NotificationHandler类中,没有ViewModel,所以我相信我将需要使用自定义协程范围来获取数据。我想尽可能远离Main线程执行此操作,因为我的通知可以由Alarm Manager触发,因此该应用可能无法打开。
下面我尝试使用runBlocking
和suspended fun getQuotesFromRepository()
,但是由于使用DAO从数据库未返回任何内容,因此添加的NullPointerException
被抛出。需要明确的是,我希望在调用defaultQuoteRepository.allQuotes
时取回getQuotesFromRepository()
的值。
任何帮助将不胜感激。预先感谢。
// Package and imports ...
class NotificationHandler(private val context: Context) {
fun createNotificationChannel() {
// Creates notification channel...
}
suspend fun getQuotesFromRepository() = withContext(Dispatchers.IO) {
val defaultQuoteDao = QuoteDatabase.getDatabase(context,this).defaultQuoteDao() // this refers to the scope
val defaultQuoteRepository = DefaultQuoteRepository(defaultQuoteDao)
return@withContext defaultQuoteRepository.allQuotes
}
fun displayNotification() {
val listOfQuotes = runBlocking {
getQuotesFromRepository()
}
val quote = listOfQuotes.value?.let {
val size = it.size
val randomIndex = (0..size).random()
it[randomIndex]
} ?: throw NullPointerException("Quotes not found")
// Intent stuff ...
val builder = NotificationCompat.Builder(context,PUSH_NOTIFICATION_CHANNEL_ID)
// Some other values..
.setContentText("${quote.quote} - ${quote.author}")
.setStyle(
NotificationCompat.BigTextStyle()
.bigText("${quote.quote} - ${quote.author}")
)
with(NotificationManagerCompat.from(context)) {
notify(0,builder.build())
}
}
private companion object {
...
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。