[英]Cannot handover value from Activity to Repository to pass it into Dao method
I have a vocabulary room-database where words are divided into 4 categories (indicated in respective field of the table).我有一个词汇室数据库,其中单词分为 4 个类别(在表格的各个字段中表示)。
When the Activity launches, the method getWords()
from Dao is triggered with the required argument being passed by WorkActivity
当 Activity 启动时,来自 Dao 的方法
getWords()
被触发,所需的参数由WorkActivity
传递
On launching the Activity I get the following error在启动活动时,我收到以下错误
Cannot create an instance of class space.rodionov.englishwanker.WordViewModel.
Where did I go wrong?我在哪里 go 错了? Any help is appreciated
任何帮助表示赞赏
In Dao:在道:
@Query("SELECT * FROM word_table WHERE category IN(:filterCategory) ORDER BY RANDOM() LIMIT 4")
Single<List<Word>> get4words(List<Integer> filterCategory);
In Repository:在存储库中:
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;
}
In ViewModel:在视图模型中:
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
In WorkActivity:在工作活动中:
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
}
Answer is I just forgot to initialize ArrayList categoryFilter
in Repository.答案是我只是忘记在存储库中初始化
ArrayList categoryFilter
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.