AndroidViewModel更新MutableLiveData对象

时间:2018-01-01 22:31:09

标签: android-room

我在ViewModel中初始化布尔属性时遇到问题。我不确定正确的方法。

我对主活动有一个Switch控件,如果我更改了开关,我想更改boolean startsWith值。根据布尔值,我将调用相应的Dao函数。

我正在尝试初始化该值,但不确定如何执行此操作。我是否应该观察布尔值,我应该使用双向绑定,这个属性应该是MutableLiveData吗?

wordListViewModel = ViewModelProviders.of(this).get(WordListViewModel.class);
wordListViewModel.setStartsWith(true);

我收到此错误,甚至无法启动Activity:

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);
            });

    }

1 个答案:

答案 0 :(得分:1)

我想我明白了。检查必须在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);
    });