本文介绍了LiveData.getValue()返回Room的null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Java POJO对象
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;
}
}
我的查询方法
@Query("SELECT * FROM section")
LiveData<List<Section>> getAllSections();
访问数据库
final LiveData<List<Section>> sections = mDb.sectionDAO().getAllSections();
在下一行中,我正在检查sections.getValue()
,尽管我在数据库中有数据,但始终为空,后来我在onChanged()
方法中获取了值.
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){
}
});
但是当我从查询中省略LiveData时,我正在按预期方式获取数据.查询方法:
But when I omit LiveData from the query I am getting the data as expected.Query Method:
@Query("SELECT * FROM section")
List<Section> getAllSections();
访问数据库:
final List<Section> sections = mDb.sectionDAO().getAllSections();
推荐答案
我通过这种方法解决了这个问题
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;
}
这篇关于LiveData.getValue()返回Room的null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!