gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 23:27:11 25 4
gpt4 key购买 nike

我正在使用带有 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/

25 4 0
文章推荐: javascript - 只打印
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com