javaandroiddatabaseandroid-room

Why is my LiveData not getting retrieved from the Room Database and update automatically?


This is how I have set up my DAO

@Query("SELECT * FROM alarm_table order by id")
List<AlarmEntity> getAllAlarms();

and I have the following in my viewmodel class

private MutableLiveData<List<AlarmEntity>> allAlarms;
public AlarmViewModel(@NonNull Application application) {
    super(application);
    dataBAse = RoomDB.getInstance(application.getApplicationContext());
    allAlarms = new MutableLiveData<>();
    loadAlarms();
}

//getting all alarms from database
private void loadAlarms() {
    AppExecutors.getInstance().diskIO().execute(new Runnable() {
        @Override
        public void run() {
            List<AlarmEntity> alarmItems =  dataBAse.alarmDao().getAllAlarms();
            allAlarms.postValue(alarmItems);
            Log.d(TAG, "run: "+alarmItems);
        }
    });
}
//passing the data to main Fragment for displaying
public LiveData<List<AlarmEntity>> getAllAlarms() {
    return allAlarms;
}

and this is my observer in fragment

viewModel.getAllAlarms().observe(getViewLifecycleOwner(), new Observer<List<AlarmEntity>>() {
    @Override
    public void onChanged(List<AlarmEntity> alarmEntities) {
        alarmEntityList.addAll(alarmEntities);
    }
});

I'm a bit confused since my LiveData oes not automatically update when I add a new record to my Room Database,

Im expecting auto updates on it's own without me having to call the getAll() method everytime I add a new Item. When you have LiveData, does the Android OS shoul should auto update this List when you add/delete/update a record in the Database? Thanks.


Solution

  • Change your DAO to return a LiveData:

    LiveData<List<AlarmEntity>> getAllAlarms();
    

    You now only have one return object from the database, but this LiveData object is updated everytime something changes in the database. If you observe this LiveData, you will always be up-to-date.

    Also see here: https://developer.android.com/training/data-storage/room/async-queries#options