簡體   English   中英

Android Room LiveData 選擇查詢參數

[英]Android Room LiveData select query parameters

我決定通過做一個簡單的數據庫應用程序來自學 Java 和 Android。 我已經以“懶惰”的方式實現了一些功能——所有的選擇都是在主線程上完成的。

現在我想使用 LiveData 進行選擇。 我已經閱讀了關於 android 開發人員簡單培訓指南,並使用 LiveData 和 RecyclerView 從 codelabs 指南中實現了一個更復雜的解決方案 整個表的插入、更新、刪除和選擇工作完美無缺,但是我不知道如何將參數傳遞給選擇。

示例:我有一個包含所有記錄的可滾動列表的活動,我想對列表應用一些過濾器(搜索)。 據我了解,來自 DAO 的實際 select 方法僅被調用一次(創建 ViewModel 時),那么如何使用新參數更新查詢?

其他示例:我有其他活動顯示記錄的所有列(用於查看和編輯)。 如何將 id 傳遞給查詢以選擇單行?

我的數據庫代碼與此代碼實驗室中的代碼不太一樣

編輯:我終於這樣做了:每次我想更新查詢參數時,我都會從 DAO(通過 ViewModel 和 Repo)調用 select 並將一個新的觀察者添加到該新列表中。 這個解決方案似乎不是最佳的,但我想它有效......

我認為您的解決方案是 Transformations.switchMap。 最簡單的例子,它在代碼實驗室的情況下如何工作

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 的值

我希望這對你有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM