【问题标题】:List<> from Room Database is always null房间数据库中的 List<> 始终为空
【发布时间】:2018-03-14 01:05:32
【问题描述】:

以下类用于将调查列表存储在 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
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 */
}

使用所有这些,我设置了一个片段,它有一个显示调查列表的 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);
            }
        }
    });
}

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

【问题讨论】:

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


    【解决方案1】:

    您的onChanged 实际上并没有使用它给出的surveys 参数,将其更改为调用setSurveyData(surveys) 来实际填写您的数据。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-02
        • 1970-01-01
        • 1970-01-01
        • 2019-12-10
        • 1970-01-01
        • 2018-08-18
        相关资源
        最近更新 更多