Search code examples
androidandroid-roomandroid-architecture-componentsandroid-livedata

LiveData.getValue() returns null with Room


Java POJO Object

public class Section {

    @ColumnInfo(name="section_id")
    public int mSectionId;

    @ColumnInfo(name="section_name")
    public String mSectionName;

    public int getSectionId() {
        return mSectionId;
    }

    public void setSectionId(int mSectionId) {
        this.mSectionId = mSectionId;
    }

    public String getSectionName() {
        return mSectionName;
    }

    public void setSectionName(String mSectionName) {
        this.mSectionName = mSectionName;
    }
}

My Query method

@Query("SELECT * FROM section")
LiveData<List<Section>> getAllSections();

Accessing DB

final LiveData<List<Section>> sections = mDb.sectionDAO().getAllSections();

On the next line I am checking sections.getValue() which is always giving me null although I have data in the DataBase and later I am getting the value in the onChanged() method.

sections.observe(this, new Observer<List<Section>>() {
    @Override
    public void onChanged(@Nullable List<Section> sections){

    }
});

But when I omit LiveData from the query I am getting the data as expected. Query Method:

@Query("SELECT * FROM section")
List<Section> getAllSections();

Accessing DB:

final List<Section> sections = mDb.sectionDAO().getAllSections();

Solution

  • I solve this problem through this approach

        private MediatorLiveData<List<Section>> mSectionLive = new MediatorLiveData<>();
        .
        .
        .
    
        @Override
        public LiveData<List<Section>> getAllSections() {
            final LiveData<List<Section>> sections = mDb.sectionDAO().getAllSections();
    
            mSectionLive.addSource(sections, new Observer<List<Section>>() {
                @Override
                public void onChanged(@Nullable List<Section> sectionList) {
                   if(sectionList == null || sectionList.isEmpty()) {
                      // Fetch data from API
                   }else{
                      mSectionLive.removeSource(sections);
                      mSectionLive.setValue(sectionList);
                   }
                }
            });
            return mSectionLive;
        }