有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法将值从活动转移到存储库以将其传递到Dao方法

我有一个词汇室数据库,其中的单词分为4类(在表格的相应字段中显示)

当活动启动时,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;
    }
    

在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

在工作活动中:

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
    }

共 (1) 个答案

  1. # 1 楼答案

    答案是我忘了在存储库中初始化ArrayList categoryFilter