- 创建一个类来保存每列的最大/最小值
public class ColumnMinMax {
private Double maxVal;
private Double minVal;
public ColumnMinMax(Double maxVal, Double minVal) {
this.maxVal = maxVal;
this.minVal = minVal;
}
public Double getMaxVal() {
return maxVal;
}
public Double getMinVal() {
return minVal;
}
}
- 创建一个DAO,执行查询并返回包含每列最大/最小值的列表
@Dao
public interface MyDao {
@Query("SELECT MAX(column1) as max1, MIN(column1) as min1," +
"MAX(column2) as max2, MIN(column2) as min2," +
"MAX(column3) as max3, MIN(column3) as min3 " +
"FROM my_table")
LiveData> getColumnMinMax();
}
- 在ViewModel中调用此DAO方法
public class MyViewModel extends ViewModel {
private final LiveData> columnMinMaxLiveData;
public MyViewModel(MyDao myDao) {
columnMinMaxLiveData = myDao.getColumnMinMax();
}
public LiveData> getColumnMinMaxLiveData() {
return columnMinMaxLiveData;
}
}
- 在Activity或Fragment中观察LiveData并使用数据
myViewModel.getColumnMinMaxLiveData().observe(this, columnMinMaxList -> {
for (ColumnMinMax columnMinMax : columnMinMaxList) {
Double max1 = columnMinMax.getMaxVal();
Double min1 = columnMinMax.getMinVal();
// Use the values as needed
}
});