今天下午需要实现一个东西是:获取出系统联系人数据库中的raw_contact_id,使用系统提供的ContentResolver进行查询,但是一直报错,后来google了一下,发现原来在这里面是无法使用distinct的。不知道为什么。也不知道那些贴代码出来的人是怎么办到的。后来参考了一篇博文,问题算是得到解决了
Cursor cursor2 = context.getContentResolver().query( Data.CONTENT_URI, new String[]{ Data.RAW_CONTACT_ID }, " 1=1 ", null, null);
先查出所有的raw_contact_id
再利用HashSet的特性,因为向HashSet中添加记录的时候,默认会将相同的去除
这样就相当于distinct的效果啦。
HashSet<Integer> hashSet = new HashSet<Integer>(); while(cursor2.moveToNext()) { hashSet.add(cursor2.getInt(cursor2.getColumnIndex(Data.RAW_CONTACT_ID))); } System.out.println("hashSet:count:" + hashSet.size());
参考链接:http://www.oschina.net/question/163910_27486
但是这样做还是有问题,因为HashSet的访问需要使用迭代器,而我不希望所得到的数据通过迭代器来处理,因此,还可以这样处理:
while(cursorOfSys.moveToNext()) { int currRawContactId = cursorOfSys.getInt(cursorOfSys.getColumnIndex(Data.RAW_CONTACT_ID)); if(listOfSysRaw.isEmpty()) { listOfSysRaw.add(currRawContactId); } else { int sizeOfSysRaw = listOfSysRaw.size(); System.out.println("currRawContactId:" + currRawContactId + "sizeOfSysRaw:" + sizeOfSysRaw); boolean isExist =false; for(int i = 0; i < sizeOfSysRaw; i++) { if(listOfSysRaw.get(i) == currRawContactId)//如果不存在这个值 { isExist = true; break; } } if(!isExist) { listOfSysRaw.add(currRawContactId);//添加到数组里面 } } }