使用 ViewModel 和 ID 从 ROOM DB 访问数据

问题描述 投票:0回答:1

假设我在 Room DB 中有一个数据列表。 设数据为:setId、formId、formName。 单个setId中可以有多个formId。让setId 1包含10个表单,2包含5个表单。

现在我想做的是,使用 ViewModel 中的 setId 从数据库中提取数据。

让我的道是:

@Query("SELECT * FROM form WHERE setId = :id")
LiveData<List<Form>> getAllFilledForms(int id);

如何在 ViewModel 中实现这样的操作。 我想检索所有设置id相同的表单列表,让1.

编辑: 视图模型类:

public class ListSetViewModel extends AndroidViewModel {

    private final LiveData < List < FormSet >> allFormSets;
    private FormDatabase formDatabase;
    public ListSetViewModel(@NonNull Application application) {
        super(application);
        formDatabase = FormDatabase.getDatabase(application);
        allFormSets = formDatabase.formSetDao().getAllFilledForms(setId);
    }

    public LiveData < List < FormSet >> getAllFormSets(setId) {
        return allFormSets;
    }
}
android viewmodel dao android-room
1个回答
3
投票

您需要通过 Factory 或 Dagger2 向 ViewModel 注入 ID。或者您可以使用公共方法来获取数据。

public LiveData<List<FormSet>> getAllFormSets(setId){
    return allFormSets = formDatabase.formSetDao().getAllFilledForms(setId);
}
© www.soinside.com 2019 - 2024. All rights reserved.