Getting no data from the LiveData observer of a database

Znerual :

What I want

I have a Room database connected to a RecyclingView, which gets filled by a Query selecting all the data from a month. The month can be changed by the user and I want the RecyclingView to refresh the data each time the user changes the month.

Problem

The RecyclingView gets the correct data for the starting month (before the user changed the value). But after the user invokes the onNextMonthClick function, the RecyclingView is empty (which is okay for the next month) but stays empty even when we are back at the original month.

Already tried

Using my Log I found out that the onChange() method in the onNextMonthClicked() never triggers when there is data for the month but it triggers if there is no data in this month.

How can I load my data again?

month = Dates.getMonth();
mDiaryViewModel = new ViewModelProvider(this).get(DiaryViewModel.class);
mDiaryViewModel.getmEntriesMonth(month).observe(this, new Observer<List<Diary>>() {
        @Override
        public void onChanged(List<Diary> diaries) {
            adapter.setEntries(diaries);
        }
});


}
public void onNextMonthClick(View view) {
    if (month < 12) {
        month += 1;
    } else {
        month = 1;
    }
    adapter.setEntries(mDiaryViewModel.getmEntriesMonth((month)).getValue());
    mDiaryViewModel.getmEntriesMonth(month).observe(this, new Observer<List<Diary>>() {
        @Override
        public void onChanged(List<Diary> diaries) {
            adapter.setEntries(diaries);
        }
    });
}

The whole code can be found here

Pierluigi :

in your code you require a LiveData every time you call onNextMonth function, but you never unplug the old LiveData. So you have more then one observer updating RecyclerView. You should save the current LiveData and in the onNextMonth function, first you should remove its observer. The code

adapter.setEntries(mDiaryViewModel.getmEntriesMonth((month)).getValue());

could not work because the value of a LiveData is updated asynchronously, remove this line of code. The last suggestion is that if you are in a Fragment you should use viewLifecycle end not this as LifecycleOwner:

  mDiaryViewModel.getmEntriesMonth(month).observe(getViewLifecycle(), new 
             Observer<List<Diary>>() {
    @Override
    public void onChanged(List<Diary> diaries) {
        adapter.setEntries(diaries);
    }
});

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=357235&siteId=1