Reputation: 52454
I am having a problem initializing a boolean property in my ViewModel. I am not sure the right way to go about this.
I have a Switch control on the main activity, and if I change the switch I want to change the boolean startsWith value. Depending on the boolean value I will call the corresponding Dao function.
I am trying to initialize the value, but not sure how to do this. Should I observe the boolean value, should I use two way binding, should this property be MutableLiveData?
wordListViewModel = ViewModelProviders.of(this).get(WordListViewModel.class);
wordListViewModel.setStartsWith(true);
I get this error, cannot even start Activity:
Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
Code:
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);
});
}
Upvotes: 0
Views: 2525
Reputation: 52454
I think I figured it out. The check has to be inside the switchMap function. The rest of the code only runs when the model is initialized.
I changed my code and it worked:
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);
});
Upvotes: 1