android - 当日期更改且未调用 onCreate 时更改数据库中观察到的行

标签 android kotlin android-room android-livedata

我正在使用带有 LiveData 的 Room 数据库。在主要 Activity 中,我显示了当天的数据。但是当新的一天到来并且没有调用 onCreate 时, View 会显示前一天的数据。如何在 onResume 中正确刷新我的数据/ View ?

主要 Activity :

mTodayViewModel = ViewModelProviders.of(this).get(TodayDataViewModel::class.java)
    val todayDataObserver = Observer<CoffeeProductivityData> { todayData ->
        ... update views here }

    mTodayViewModel.getTodayData().observe(this, todayDataObserver)

View 模型:

class TodayDataViewModel(application: Application) : AndroidViewModel(application) {

private val mRepository: CoffeeProductivityRepository = CoffeeProductivityRepository(application)
private val mTodayData: LiveData<CoffeeProductivityData> by lazy {
    mRepository.getTodayData()
}

fun getTodayData(): LiveData<CoffeeProductivityData> {
    return mTodayData
}}

存储库:

private var mCoffeeProductivityDao: CoffeeProductivityDao
private var mTodayData: LiveData<CoffeeProductivityData>
private var mUtilities: Utilities

init {
    val database: CoffeeProductivityDatabase = CoffeeProductivityDatabase.getDatabase(application)!!
    mCoffeeProductivityDao = database.coffeeProductivityDao()
    mUtilities = Utilities()
    mTodayData = mCoffeeProductivityDao.getTodayData(mUtilities.getTodayDate())
}

// Wrapper for getting current day data
fun getTodayData(): LiveData<CoffeeProductivityData> {
    return mTodayData
}

来自 DAO 的查询:

@Query("SELECT * from coffee_productivity WHERE date LIKE :todayDate")
fun getTodayData(todayDate: String): LiveData<CoffeeProductivityData>

最佳答案

我认为您最好的选择是收听 ACTION_TIME_TICK 广播操作。

这是一个例子:https://gist.github.com/sourabh86/6826730

来自文档:

The current time has changed. Sent every minute. You cannot receive this through components declared in manifests, only by explicitly registering for it with Context.registerReceiver()

if (time == midnight)
    refreshDataManually();

检查 this question出,关于如何手动刷新您的 LiveData。

关于android - 当日期更改且未调用 onCreate 时更改数据库中观察到的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53360972/

相关文章:

android - 是否可以向monkeyrunner脚本发送一些参数

android - 如何将我的应用程序旋转 180 度倒置旋转设备 180 度倒置?

kotlin - typeof关键字是什么

unit-testing - 我怎样才能只开课来测试课?

android - Room 无法在 Android 中验证数据完整性

android - minSdkVersion小于11时如何添加Holo Style Horizo​​ntal ProgressBar?

kotlin - "parallelStream()"和 "asSequence().asStream().parallel()"之间的区别

安卓机房 : Each bind variable in the query must have a matching method

android - 如何处理Room中嵌套的1对1对象中的关系数据(将ForeignKey转换为对象)

java - 日历日期不同