简体   繁体   中英

Android Room LiveData select query parameters

I decided to teach myself Java and Android by doing a simple database app. I already implemented some functionality the "lazy" way - all selects are done on the main thread.

Now I want to use LiveData for selects. I've read the simplistic training guide on android developers and implemented a more complex solution from codelabs guide , with LiveData and RecyclerView. Inserts, updates, deletes, and selects for whole tables work flawlessly, however I have no idea how to pass parameters to selects.

Example: I have an activity with scrollable list of all records and I want to apply some filters to the list (search). From what I understand the actual select method from DAO is called only once (when ViewModel is created), so how do I update query with new parameters?

Other example: I have other activity that displays all columns of a record (for viewing and editing). How do I pass id to query to select a single row?

My database code is more less the same as in this codelab

Edit: I finally did it like that: every time I want to update query parameters I call select from DAO (through ViewModel and Repo) and add a new observer to that new list. This solution doesn't seem optimal but I guess it works...

I think your solution is a Transformations.switchMap. The simplest example how it may works in the case from codelab

public class WordViewModel extends AndroidViewModel {
    private WordRepository mRepository;
    private LiveData<List<Word>> mAllWords;
    private LiveData<List<Word>> searchByLiveData;
    private MutableLiveData<String> filterLiveData = new MutableLiveData<>();

    public WordViewModel (Application application) {
        super(application);
        mRepository = new WordRepository(application);
        mAllWords = mRepository.getAllWords();
        searchByLiveData = Transformations.switchMap(filterLiveData, 
                                                     v -> mRepository.searchBy(v));
    }

    LiveData<List<Word>> getSearchBy() { return searchByLiveData; }
    void setFilter(String filter) { filterLiveData.setValue(filter); }
    LiveData<List<Word>> getAllWords() { return mAllWords; }
    public void insert(Word word) { mRepository.insert(word); }
}

So, when you set filter value, it will change value of searchByLiveData

I hope this helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM