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

时间:2018-11-18 12:39:55

标签: android kotlin android-room android-livedata

我正在将Room数据库与LiveData一起使用。在主要活动中,我正在显示当天的数据。但是,当新的一天到来且未调用onCreate时,视图将显示前一天的数据。如何在onResume中正确刷新数据/视图?

MainActivity:

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

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

ViewModel:

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>

2 个答案:

答案 0 :(得分:1)

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

下面是一个示例:https://gist.github.com/sourabh86/6826730

从文档中:

  

当前时间已更改。每分钟发送一次。您不能通过清单中声明的​​组件来接收此消息,只能通过向Context.registerReceiver()

进行显式注册来实现。
if (time == midnight)
    refreshDataManually();

查看this question,了解如何手动刷新LiveData。

答案 1 :(得分:0)

我无法正确重置LiveData,所以我结束了重新启动活动的过程。我之所以决定这样做是因为在我的应用程序用例中,这种情况非常少见。 广播接收器在活动onCreate中注册,而在onDestroy中未注册。 这是广播接收器,它会在日期更改时进行监听:

    // Broadcast receiver for detecting change of day (need to refresh MainActivity)
private val mDayChangedReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action == Intent.ACTION_DATE_CHANGED) {
            isActivityRefreshNeeded = true
            Log.d("mDayChangedReceiver", "Received DAY_CHANGED broadcast")
        }
    }
}

然后,如果boolean isActivityRefreshNeeded为true,我将在MainActivity的onResume中进行检查。如果是,我重置活动:

// If User has changed settings and navigated via back button, or day changed, refresh activity
    when (isActivityRefreshNeeded) {
        true -> {
            isActivityRefreshNeeded = false
            refreshActivity()
        }
    }

这不是最佳解决方案,但正如我所说,当需要刷新时,这种情况很少见。 如果有人有更好的解决方案,我将很高兴看到并实施。