gpt4 book ai didi

android - 为什么不调用实时数据观察方法?

转载 作者:行者123 更新时间:2023-11-29 00:58:28 24 4
gpt4 key购买 nike

我在我的 android 应用程序中使用 Room 和 livedata,但我无法在 livedata 中获取数据,我尝试了所有方法。最后一种方法是使用 observe 方法,它给我一个列表,但是没有调用这个方法,我该如何解决这个问题?

这是我的 Dao 界面

@Dao
public interface QuestionTemplateDao {

@Query("SELECT question_template_table.ID,question_template_table.Text,question_template_table.FieldNo from question_template_table where question_template_table.FieldNo = :fieldNO")
LiveData<List<QuestionTemplate>> getTemplate(int fieldNO);

}

这是我的仓库

public LiveData<List<QuestionTemplate>> getmAllQuestionTemplates(int field) {
if(questionTemplateDao==null)
questionTemplateDao=db.questionTemplateDao();
mQuestionTemplates=questionTemplateDao.getTemplate(field);
return mQuestionTemplates;
}

这是 View 模型

templateLiveData = mRepository.getmAllQuestionTemplates(selectedField);
templateList = new ArrayList<>();
templateLiveData.observe(activity, new Observer<List<QuestionTemplate>>() {
@Override
public void onChanged(@Nullable List<QuestionTemplate> questionTemplates) {
Log.e("onChanged","onChanged");
if (questionTemplates != null) {
templateList.addAll(questionTemplates);
}
}
});

最佳答案

如果在 ViewModel 中直接这样使用会怎样:

templateList = new ArrayList<>();
mRepository
.getmAllQuestionTemplates(selectedField)
.observe(activity, new Observer<List<QuestionTemplate>>() {
@Override
public void onChanged(@Nullable List<QuestionTemplate> questionTemplates) {
Log.e("onChanged","onChanged");
if (questionTemplates != null) {
templateList.addAll(questionTemplates);
}
}
});

无需在ViewModel中获取新的LiveData对象,您也可以直接从返回给您的LiveData中观察。


编辑:

检查另一个解决方法,

您的 DAO 将是这样的:

@Dao
public interface QuestionTemplateDao {

@Query("SELECT question_template_table.ID,question_template_table.Text,question_template_table.FieldNo from question_template_table where question_template_table.FieldNo = :fieldNO")
List<QuestionTemplate> getTemplate(int fieldNO);

}

你的仓库,

public void getmAllQuestionTemplates(int field, MutableLiveData<List<QuestionTemplate>> liveData) {
if(questionTemplateDao==null)
questionTemplateDao=db.questionTemplateDao();
liveData.setValue(questionTemplateDao.getTemplate(field));
}

你的 View 模型,

mRepository.getmAllQuestionTemplates(selectedField, (MutableLiveData<List<QuestionTemplate>>) templateLiveData);
templateList = new ArrayList<>();
templateLiveData.observe(activity, new Observer<List<QuestionTemplate>>() {
@Override
public void onChanged(@Nullable List<QuestionTemplate> questionTemplates) {
Log.e("onChanged","onChanged");
if (questionTemplates != null) {
templateList.addAll(questionTemplates);
}
}
});

关于android - 为什么不调用实时数据观察方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52855694/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com