问题描述
我有一个词汇室数据库,其中的单词分为 4 类(在表格的各个字段中指明)。
当 Activity 启动时,来自 Dao 的方法 getWords()
被触发,所需参数由 WorkActivity
传递
启动活动时出现以下错误
Cannot create an instance of class space.rodionov.englishwanker.WordViewModel.
我哪里做错了?任何帮助表示赞赏
在道中:
@Query("SELECT * FROM word_table WHERE category IN(:filterCategory) ORDER BY RANDOM() LIMIT 4")
Single<List<Word>> get4words(List<Integer> filterCategory);
在存储库中:
public class WordRepository {
private ArrayList<Integer> categoryFilter;
private WordDao mWordDao;
//other variables
WordRepository(Application application) {
WordDatabase db = WordDatabase.getDatabase(application);
mWordDao = db.WordDao();
clearFilter();
setFilter(categoryFilter);
m4words = mWordDao.get4words(categoryFilter);
}
public void clearFilter(){
categoryFilter.clear();
}
public void setFilter(ArrayList<Integer> categoryFilter) {
this.categoryFilter = categoryFilter;
}
在视图模型中:
private ArrayList<Integer> categoryFilter = new ArrayList<>();
private WordRepository mRepository;
// declaring variables
public WordViewModel(@NonNull Application application) {
mRepository = new WordRepository(application);
//declaring
mRepository.setFilter(categoryFilter);
m4words = mRepository.get4words();
}
public void clearFilter() {
categoryFilter.clear();
}
public void setFilter(ArrayList<Integer> categoryFilter) {
this.categoryFilter = categoryFilter;
}
//other methods
在工作活动中:
private WordViewModel wordViewModel;
public ArrayList<Integer> categoryFilter = new ArrayList<>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPreferences = getSharedPreferences("save",MODE_PRIVATE);
boolean category0 = sharedPreferences.getBoolean("Category0",true);
boolean category1 = sharedPreferences.getBoolean("Category1",true);
//other catigories from memory ...
//
wordViewModel = new ViewModelProvider(this,ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication()))
.get(WordViewModel.class);
wordViewModel.getListLivedata().observe(this,words -> {
adapter.submitList(words);
});
//
wordViewModel.clearFilter();
if (category0 == true) {
categoryFilter.add(0);
Log.d(TAG,"onCreate: common_words added: called");
}
//other categories
wordViewModel.setFilter(categoryFilter);
//other methods
//buildRecyclreVeiw
}
解决方法
答案是我刚刚忘记在 Repository 中初始化 ArrayList categoryFilter
。