LiveData.getValue() 在 Room 中返回 null

新手上路,请多包涵

Java POJO 对象

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() 方法中获取值。

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

    }
});

但是当我从查询中省略 LiveData 时,我得到了预期的数据。查询方式:

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

访问数据库:

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

原文由 S Haque 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

我通过这种方法解决了这个问题

    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;
    }

原文由 S Haque 发布,翻译遵循 CC BY-SA 3.0 许可协议

在下一行中,我正在检查 sections.getValue() ,尽管我在数据库中有数据,但它总是给我 null ,后来我在 onChanged() 方法中获取值。

这是正常行为,因为返回 LiveData 的查询是异步工作的。该值此时为空。

所以调用这个方法

LiveData<List<Section>> getAllSections();

你稍后会在这里得到结果

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

}
});

来自文档:

除非您在构建器上调用 allowMainThreadQueries() ,否则 Room 不允许在主线程上访问数据库,因为它可能会长时间锁定 UI。异步查询(返回 LiveData 或 RxJava Flowable 的查询)不受此规则约束,因为它们在需要时在后台线程上异步运行查询。

原文由 snersesyan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题