LiveData.getValue() returns null with Room

前端 未结 7 898
无人及你
无人及你 2020-12-05 13:16

Java POJO Object

public class Section {

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

    @ColumnInfo(name=\"section_name\")
    public S         


        
7条回答
  •  情书的邮戳
    2020-12-05 14:13

    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.

    This is a normal behavior, because queries that return LiveData, are working asynchronous. The value is null that moment.

    So calling this method

    LiveData> getAllSections();
    

    you will get the result later here

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

    from documentation:

    Room does not allow accessing the database on the main thread unless you called allowMainThreadQueries() on the builder because it might potentially lock the UI for a long periods of time. Asynchronous queries (queries that return LiveData or RxJava Flowable) are exempt from this rule since they asynchronously run the query on a background thread when needed.

提交回复
热议问题