Android:能够返回ArrayList但不能返回LiveData数组列表

时间:2019-06-08 19:15:54

标签: android android-livedata

我无法从Room数据库中获取LiveData ArrayList,但能够检索标准的ArrayList,无法弄清原因。

我已在调试模式下运行此代码,并且ArrayList返回的大小应为4。当使用get值时,LiveData ArrayList返回null。我已经在执行程序内和执行程序外运行了LiveData查询,它返回null。

声明

public LiveData<List<CourseEntity>> courseEntities;
private List<CourseEntity> courseData = new ArrayList<>();

执行者以外的代码

public void loadData(final int termId) {

        courseEntities = courseRepository.getCourseByTermId(termId);
        courseData = courseEntities.getValue();

}

执行器内部的代码

public void loadData(final int termId) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                courseEntities = courseRepository.getCourseByTermId(termId);
                courseData = courseEntities.getValue();

            }
        });
    }

仅使用ArrayList的代码

public void loadData(final int termId) {
        executor.execute(new Runnable() {
            @Override
            public void run() {

                courseData = courseRepository.getCourseByTerm(termId);
            }
        });
    }

来自道的查询

@Query("SELECT * FROM course " +
            "WHERE term_id = :termIdSelected ORDER BY course_start" )
    LiveData<List<CourseEntity>> getCourseByTermId(int termIdSelected);

    @Query("SELECT * FROM course WHERE term_id = :termIdSelected ORDER BY course_start")
    List<CourseEntity> getCourseByTerm(int termIdSelected);

这将为LiveData生成一个空值,而不是像普通ArrayList那样为4。唯一的区别是结果的LiveData包装器。别人可以分享的任何智慧都会受到赞赏。

1 个答案:

答案 0 :(得分:1)

当您有一个会议室@Dao时,返回LiveData(或RxJava类型,例如ObservableSingle),则生成的实现将在后台执行实际的工作线。因此,当getCourseByTermId()返回时,工作尚未开始,因此LiveData尚无结果。

LiveData这样的反应性类型应被观察到。因此,您的活动/片段/无论发生什么,observe() LiveData都会对结果产生反应。

相关问题