【发布时间】:2018-05-16 10:04:11
【问题描述】:
我正在关注 google tutorial 的房间持久性,但我卡住了,现在我的教程一切正常,但我需要扩展它并能够将参数传递给 ViewModel,因为我需要能够向 repo 提交不同的查询,也许我错了,但现在我在ViewModel 中这样做,它应该能够读取他的字段并选择正确的方法与 repo 交谈.
WordViewModel:
public class WordViewModel extends AndroidViewModel {
private WordRepository mRepository;
private LiveData<List<Word>> mAllWords;
public int mode = 0;
public WordViewModel (Application application) {
super(application);
mRepository = new WordRepository(application);
if (mode==0)
mAllWords = mRepository.getAllWords();
else
mAllWords = mRepository.getSomethingElse();
}
LiveData<List<Word>> getAllWords() { return mAllWords; }
public void insert(Word word) { mRepository.insert(word); }
}
然后在活动中触发我们得到这个的模型视图
mWordViewModel = ViewModelProviders.of(this).get(WordViewModel.class);
mWordViewModel.mode=1; //MY ADDITION, not working
...
mWordViewModel.getAllWords().observe(this, new Observer<List<Word>>() {
@Override
public void onChanged(@Nullable final List<Word> words) {
// Update the cached copy of the words in the adapter.
adapter.setWords(words);
}
});
...
现在的问题是我所做的字段访问和编辑(“模式”字段)不起作用,就像实际调用 ViewModel 时该字段正在重置,所以它始终为 0。什么我失踪了吗?考虑到该模式仅用于解释并且最终我需要很多参数,最简单的解决方法是什么(因此创建各种ViewModel 不是一种选择)
【问题讨论】:
-
将
mode设为静态并在初始化前更改其值 -
@AbuYousuf “在初始化之前”是什么意思?仅将字段更改为静态什么都不做
-
在初始化
mWordViewModel之前添加WordViewModel.model = 1 -
@AbuYousuf 成功了!
标签: android persistence viewmodel android-room