我在初始化ViewModel中的布尔属性时遇到问题。我不确定做这件事的正确方式。
我在主活动上有一个开关控制,如果我改变开关,我想要改变布尔值startsWith。根据布尔值,我将调用相应的Dao函数。
我正在尝试初始化值,但不确定如何执行此操作。我应该观察布尔值,我应该使用双向绑定,这个属性应该是MutableLiveData吗?
wordListViewModel = ViewModelProviders.of(this).get(WordListViewModel.class);
wordListViewModel.setStartsWith(true);我收到这个错误,甚至无法启动活动:
Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference代码:
public class WordListViewModel extends AndroidViewModel {
final MutableLiveData<String> searchText = new MutableLiveData<>();
final MutableLiveData<Boolean> startsWith = new MutableLiveData<>();
private final LiveData<List<WordEntity>> list;
private AppDatabase appDatabase;
public WordListViewModel(Application application) {
super(application);
appDatabase = AppDatabase.getDatabase(this.getApplication());
if (startsWith.getValue() == true)
list = Transformations.switchMap(searchText, searchText -> {
return appDatabase.wordDao().getWordsStartingWith(searchText);
});
else
list = Transformations.switchMap(searchText, searchText -> {
return appDatabase.wordDao().getWordsLike(searchText);
});
}发布于 2018-01-02 08:50:29
我想我想通了。检查必须在switchMap函数内部。其余代码仅在模型初始化时运行。
我更改了我的代码,它起作用了:
if (startsWith.getValue() == null)
startsWith.setValue(true);
list = Transformations.switchMap(searchText, searchText -> {
if (startsWith.getValue() == true)
return appDatabase.dictWordDao().getWordsStartingWith(searchText);
else
return appDatabase.dictWordDao().getWordsLike(searchText);
});https://stackoverflow.com/questions/48053777
复制相似问题