java - 如何在房间数据库中查询使用类型转换器保存的数组中的整数?
问题描述
我正在使用类型转换器在我的房间数据库中保存一个列表。现在我想查询数据库并检索列表包含特定整数的对象。例如:对象 1 列表包含整数 1、2、3,当我仅查询整数 1 时,它会检索对象 1。
这是我正在尝试的:我的实体:
@Entity(tableName = "exercises")
public class Exercise {
@PrimaryKey(autoGenerate = true)
private int id;
@ColumnInfo(name = "api_id")
private int apiId;
@ColumnInfo(name = "exercise_name")
private String exerciseName;
@ColumnInfo(name = "image_path")
private String imagePath;
@ColumnInfo(name = "youtube_key")
private String youtubeKey;
@ColumnInfo(name = "exercise_type")
private int exerciseType;
@ColumnInfo(name = "muscle_group")
private List<Integer> muscleGroup;
@ColumnInfo(name = "secondary_muscles")
private List<Integer> secondaryMuscles;
@ColumnInfo(name = "notes")
private String notes;
我的类型转换器:
@TypeConverter
public static String fromList(List<Integer> list){
Gson gson = new Gson();
String json = gson.toJson(list);
return json;
}
@TypeConverter
public static List<Integer> fromString(String string){
Type listType = new TypeToken<List<Integer>>() {}.getType();
return new Gson().fromJson(string, listType);
}
我的道:
@Query("SELECT * FROM exercises WHERE muscle_group LIKE :muscle")
LiveData<List<Exercise>> getByMuscle(List<Integer> muscle);
我的视图模型:
private LiveData<List<Exercise>> exercises;
public LiveData<List<Exercise>> getExercises(Context context, int muscleGroup){
if(exercises == null){
loadData(context, muscleGroup);
}
return exercises;
}
private void loadData(Context context, int muscleGroup){
List<Integer> muscle = Arrays.asList(muscleGroup);
AppDatabase db = AppDatabase.getInstance(context);
Log.d(TAG, "Load data from database");
exercises = db.exerciseDao().getByMuscle(muscle);
}
有人知道我想要的是否可行?还是我需要做一个像检索所有而不是在for循环中选择的工作?感谢您的投入。
解决方案
推荐阅读
- xml - 使用 XSLT 转换 JSON 文件
- php - Anti XSS PHP Library (Class 'voku\\helper\\AntiXSS')
- google-apps-script - 使用 .getValues() 中的 set.Values() 时如何忽略空单元格
- javascript - 如何使用 Mocha 在客户端 WebSocket 上进行测试?接收 ReferenceError:未定义 WebSocket
- typescript - 标记日期格式字符串
- android - Flutter WillPopScope 对我来说正常工作,但是当我导航或推回同一页面时它不起作用
- android - 启动测试用例时出现自动化测试错误
- laravel - 有什么方法可以在控制器中循环一个函数以进行多数据验证?
- javascript - 在 JavaScript 中检查变量是否为数组的最有效方法?
- javascript - 以角度着色单元格xlsx