Android 联系人查询结果的排序问题

      最近,有需要要查询Android 1.6联系人的数据库,而且需要将查询出来的联系人排好顺序。按照ContentResolver的query函数的文档,它的原型为:

query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)

第二个参数为返回结果的列数,第三、四个参数对应SQL语句中的where后面的部分,最后一个参数是SQL语句中的order by后面的部分。

第三、四个参数可以用来模糊查询,比如下面的用法:

query(People.CONTENT_URI, null, People.NAME + " LIKE ?", new String[] { "%M%" }, People.NAME + " collate NOCASE DESC");

      这句话等价于SQL语句的:

select * from people where name like '%M%' order by name collate NOCASE desc;

这句话的意思是查询数据表为people的name字段中包含M的联系人。

由于,query是android对select语句的封装,应此可以将name like放在第三个参数中,带单引号的值放在第四个参数中,当然,也可以将第三个参数改为People.NAME + “ LIKE ‘%M%'",而第四个参数则为null,也即如下的形式:

query(People.CONTENT_URI, null, People.NAME + " LIKE '%M%'", null, People.NAME + " collate NOCASE DESC");

很明显,第四个参数用来表示第三个参数的?号部分,而且是可以省略单引号的。

让我们来看一下第五个参数,由于name列在数据库中collate属性被定义为LOCALIZED。因此,参照sqlite的文档,需要加collate说明(,6.0节),具体可参考如下说明:

When SQLite compares two strings, it uses a collating sequence or collating function (two words for the same thing) to determine which string is greater or if the two strings are equal. SQLite has three built-in collating functions: BINARY, NOCASE, and RTRIM.

BINARY - Compares string data using memcmp(), regardless of text encoding.
      NOCASE - The same as binary, except the 26 upper case characters of ASCII are folded to their lower case equivalents before the comparison is performed. Note that only ASCII characters are case folded. SQLite does not attempt to do full UTF case folding due to the size of the tables required.
      RTRIM - The same as binary, except that trailing space characters are ignored.

也就是说,它是用来指定排序规则,若不指定,sqlite expert中执行时会报错。但是,由于android的封装,第5个参数的collate部分可以省略(估计android默认替你选了一个)。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwzwpy.html