Android Room LiveData 选择查询参数 [英] Android Room LiveData select query parameters
问题描述
我决定通过做一个简单的数据库应用来自学 Java 和 Android.我已经以懒惰"的方式实现了一些功能 - 所有选择都在主线程上完成.
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.
现在我想使用 LiveData 进行选择.我已经阅读了 android 开发人员的简单培训指南 和实施了来自代码实验室指南的更复杂的解决方案,使用LiveData 和 RecyclerView.插入、更新、删除和选择整个表工作完美,但我不知道如何将参数传递给选择.
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.
示例:我有一个包含所有记录的可滚动列表的活动,我想对列表应用一些过滤器(搜索).据我了解,来自 DAO 的实际 select 方法仅被调用一次(在创建 ViewModel 时),那么如何使用新参数更新查询?
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?
其他示例:我有其他活动显示记录的所有列(用于查看和编辑).如何将 id 传递给查询以选择单行?
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?
我的数据库代码与此代码实验室
我终于这样做了:每次我想更新查询参数时,我都会从 DAO(通过 ViewModel 和 Repo)调用 select 并将一个新的观察者添加到该新列表中.这个解决方案似乎不是最佳的,但我想它有效......
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...
推荐答案
我认为您的解决方案是 Transformations.switchMap.最简单的例子,它在代码实验室的情况下如何工作
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); }
}
因此,当您设置过滤器值时,它会更改 searchByLiveData 的值
So, when you set filter value, it will change value of searchByLiveData
希望对你有帮助.
这篇关于Android Room LiveData 选择查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!