使用自定义协程作用域访问数据库内容

问题描述

目前,在遵循这些教程之后,我有一个使用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触发,因此该应用可能无法打开。

下面我尝试使用runBlockingsuspended 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 (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...