关于系统提供的ContentResolver无法进行distinct查询

今天下午需要实现一个东西是:获取出系统联系人数据库中的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);//添加到数组里面
				}
			}
		 }
 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值