java - 通过 Dao、Repository 和 Viewmodel 从 Room 数据库接收对象列表的问题。找不到错误
问题描述
我在 Dao、Repository、ViewModel 和 Activity 中有方法来获取人员列表,但最后我得到空列表(空对象引用错误)。哪里可能出错?非常感谢..
个人道:
@Dao
public interface PersonDao {
//other methods of PersonDao
@Query("SELECT * FROM person_table WHERE status = :status ORDER BY RANDOM() LIMIT 5")
List<Person> getFivePersonsFrom(String status);
}
在 PersonRepository 中:
public class PersonRepository {
private PersonDao mPersonDao;
private List<Person> mFivePersonsFrom;
//other methods
List<Person> getFivePersonsFrom(String status) {
PersonRoomDatabase.databaseWriteExecutor.execute(() -> {
mPersonDao.getFivePersonsFrom("noob");
});
return mFivePersonsFrom;
}
}
在 PersonViewModel 中:
public class PersonViewModel extends AndroidViewModel {
private PersonRepository mRepository;
public List<Person> mFivePersonsFrom;
public PersonViewModel(@NonNull Application application) {
super(application);
mRepository = new PersonRepository(application);
mFivePersonsFrom = mRepository.getFivePersonsFrom("noob");
//other methods
}
public List<Person> getFivePersonsFrom() {
mRepository.getFivePersonsFrom("noob");
return mFivePersonsFrom;
}
}
在 MainActivity 中:
private CardStackView noobCardStackView;
private NoobAdapter noobAdapter;
List<Person> noobList;
// other
protected void onCreate(Bundle savedInstanceState) {
noobViewModel = new ViewModelProvider(this,
ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication()))
.get(PersonViewModel.class);
noobList = noobiewModel.getFivePersonsFrom();
noobAdapter = new NoobAdapter(new NoobAdapter.NoobDiff(), noobList);
noobCardStackView.setAdapter(noobAdapter);
// methods
}
解决方案
推荐阅读
- javascript - 3个变量变成一个函数javascript?'变量是真还是假,根据结果我将其更改为字符串
- wso2 - 无法在 Siddhi 中使用“正则表达式”http 状态代码处理响应
- vue.js - vue+bulma 选项卡错误:'openTab' 已定义但从未使用
- mysql - 我可以创建一个过程或函数来删除 mysql 中的参数表吗?
- html - 如何在带有控制器和视图的 codeigniter4 中应用表单验证?
- css - 仅在触发元素下方定位 Mat-Select 选项
- visual-studio - 如何将 Visual Studio 2019 中的调试输出重定向到文件?
- php - WordPress 检查查询是否针对 pre_get_posts 过滤器中的自定义类型
- azure - 从 Azure Active Directory 中的多个租户获取用户详细信息
- mysql - MySQL JSON_EXTRACT() 查询返回 null