如何使用Room从光标获取数据

时间:2018-12-27 17:20:09

标签: android android-room

我正在使用此查询通过Room从数据库中获取数据,但无法弄清楚该查询的返回类型以及如何从该查询中获取数据

@Query("SELECT COUNT(Unit), Age as COUNT from test where Age in (1, 2, 3) and Unit in ("U5", "U6", "U4") group by Age")

下面在屏幕快照中显示了我在sqllite在线运行时获得的输出。因此,它就像键,值对。

enter image description here

1 个答案:

答案 0 :(得分:1)

步骤1:修改查询以命名两个输出:

SELECT COUNT(Unit) as count, Age from test where Age in (1, 2, 3) and Unit in ("U5", "U6", "U4") group by Age

步骤2:创建与查询输出匹配的POJO:

class AgeCounts {
  public int count;
  public int age;
}

第3步:让DAO方法(您的@Query将在其上运行)返回POJO类的一个List(例如,List<AgeCounts>),可能包装为反应性类型(例如LiveData<List<AgeCounts>>Single<List<AgeCounts>>):

@Query("SELECT COUNT(Unit) as count, Age from test where Age in (1, 2, 3) and Unit in ("U5", "U6", "U4") group by Age")
List<AgeCounts> getAgeCounts();