码迷,mamicode.com
首页 > 其他好文 > 详细

在ContentResolver中使用Group By

时间:2014-11-04 10:52:21      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   color   ar   使用   sp   div   

使用ContentProvider查询短信,希望可以在ContentResolver.query中使用Group By ,发现系统并没有提供接口或者可用字段。

探究竟

首先我们来看看query函数:

public final Cursor query(Uri uri, String[] projection,
        String selection, String[] selectionArgs, String sortOrder) {
    return query(uri, projection, selection, selectionArgs, sortOrder, null);
}

最有可能可以处理的地方就是selection,我们首先尝试设置 selection = "gourp by thread_id" 执行程序,从错误日志中发现,sql语句经过编译处理加上了括号,像下面这样:

SELECT _id, thread_id, address, person, body, date FROM sms WHERE (type=1) AND (group by thread_id) ORDER BY date DESC

看来要最终得到正确的sql语句,selection的设置需要有技巧性一些。再尝试selection = "0=0) group by (thread_id",这次成功了!主要是注意括号的处理,以及AND后面必须有一个查询条件,这里我们使用了0=0(此处验证0==0亦可)这个永真查询只是为了保证sql语句的正确性。

最后处理效果如下:

Uri SMS_PROVIDER = Uri.parse("content://sms/inbox");
String[] projection = new String[] {
  "_id", "thread_id", "address",
  "person", "body", "date"};
Cursor cursor = context.getContentResolver().query(SMS_PROVIDER,
  projection, "0=0) group by (thread_id", null, "date desc");

这样,经过编译处理之后的sql语句为:

SELECT _id, thread_id, address, person, body, date FROM sms WHERE (type=1) AND (0=0)group by (thread_id) ORDER BY date DESC

 

在ContentResolver中使用Group By

标签:des   style   blog   io   color   ar   使用   sp   div   

原文地址:http://www.cnblogs.com/noodlesonce/p/4072747.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!