I have a vocabulary room-database where words are divided into 4 categories (indicated in respective field of the table).
When the Activity launches, the method getWords()
from Dao is triggered with the required argument being passed by 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? 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
}
question from:
https://stackoverflow.com/questions/65934955/cannot-handover-value-from-activity-to-repository-to-pass-it-into-dao-method 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…