在ContentResolver中使用Group By

使用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