列表与LT;>来自Room Database始终为null

时间:2018-03-14 01:05:33

标签: android android-recyclerview android-room android-livedata

以下类用于存储Room数据库中的调查列表。 LiveData用于更新

数据库的实体类:

@Entity
public class Survey {

@PrimaryKey
@NonNull
private String surveyID;
private String surveyName;
private String url;
private double lat;
private double lng;
private  double radius;

public Survey(String surveyID, String surveyName, double lat, double lng, double radius, String url) {
    this.surveyID = surveyID;
    this.surveyName = surveyName;
    this.lat = lat;
    this.lng = lng;
    this.radius = radius;
    this.url = url;
}

各自的Dao界面:

@Dao
public interface SurveyDao {

@Query("SELECT * FROM Survey")
LiveData<List<Survey>> getListOfSurveys();

/* Rest omitted */
}

各自的存储库类

public class SurveyRepository {

private final SurveyDao surveyDao;

@Inject
public SurveyRepository (SurveyDao surveyDao){
    this.surveyDao = surveyDao;
}

public LiveData<List<Survey>> getListOfSurveys(){
    return surveyDao.getListOfSurveys();
}
/* Rest omitted */
}

视图模型:

public class SurveyCollectionViewModule extends ViewModel {

private SurveyRepository repository;

public SurveyCollectionViewModule(SurveyRepository repository) {
    this.repository = repository;
}

public LiveData<List<Survey>> getSurveys(){
    return repository.getListOfSurveys();
}
/* Rest Omitted */
}

使用所有这些,我设置了一个Fragment,它有一个显示调查列表的RecyclerView。该列表以下列方式获得:

public void onActivityCreated(Bundle savedInstanceState){
    super.onActivityCreated(savedInstanceState);

    surveyCollectionViewModule = ViewModelProviders.of(this, viewModelFactory)
            .get(SurveyCollectionViewModule.class);

    surveyCollectionViewModule.getSurveys().observe(this, new Observer<List<Survey>>() {
        @Override
        public void onChanged(@Nullable List<Survey> surveys) {
            if(SurveyListFragment.this.listOfSurveys == null) {
                setSurveyData(listOfSurveys);
            }
        }
    });
}

但是,我遇到了问题,因为此列表为getItemCount(),适配器中对NULL的调用失败。数据库不包含任何条目,但我仍然不知道为什么列表总是返回为null。

2 个答案:

答案 0 :(得分:0)

您的onChanged实际上并未使用所提供的surveys参数,请将其更改为致电setSurveyData(surveys)以实际填写您的数据。

答案 1 :(得分:0)

在ViewModel类中进行一些更改,如下所示......

    private final LiveData<List<Survey>> SurveyList;

private AppDatabase appDatabase;

public SurveyCollectionViewModule(Application application) {
    appDatabase = AppDatabase.getDatabase(this.getApplication());

    SurveyList = appDatabase.surveyDao().getAllSurvey();
}
public LiveData<List<Survey>> getSurveys() {
    return SurveyList;
}