我在模拟器设置2测试触点。
我运行下面的查询,就应该选择他们两个,填充我的域对象,并添加到列表中。因此,在底部的输出应该是2,但它是5,这是为什么? (cursor.getCount()是5,而不是2)
我已经经历了,而每次循环加强,它是retreving相同的接触多次,但与 POST code
,如不同的值电话号码
ContentResolver的CR = getContentResolver();
光标光标= cr.query(ContactsContract.Data.CONTENT_URI,
NULL,NULL,NULL,NULL);
名单< MeCercanaContact>联系人=新的ArrayList< MeCercanaContact>();
如果(cursor.getCount()大于0)
{
而(cursor.moveToNext())
{
MyContact myContact =新MyContact();
字符串给定名称= cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
字符串后code = cursor.getString(cursor.getColumnIndex(
ContactsContract.CommonDataKinds.StructuredPostal.POST code));
myContact.setFirstName(给定名称);
myContact.setLastName(交code);
contacts.add(myContact);
}
}
的System.out.println(contacts.size());
解决方案
正在查询ContactsContract.Data,这是保存的各种联系方式,如电话号码,邮寄codeS等列表的通用容器你必须过滤结果的ContactsContract.Data.MIMETYPE列等于StructuredPostal.CONTENT_ITEM_TYPE行:
所以查询更改为:
光标光标= cr.query(ContactsContract.Data.CONTENT_URI,
NULL,NULL,ContacsContract.Data.MIMETYPE +=+
ContactsContract.StructuredPostal.CONTENT_ITEM_TYPE +',NULL);
请参阅 ContactsContract.Data
I have setup 2 test contacts in my emulator.
I'm running the following query, it should pick them both out, populate my domain object, and add to a list. The output at the bottom should therefore be 2, but it is 5, why is this? (cursor.getCount() is 5 instead of 2)
I have stepped through each iteration of the while loop and it is retreving the same contact multiple times, but with different values for POSTCODE
, such as the phone number
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Data.CONTENT_URI,
null, null, null, null);
List<MeCercanaContact> contacts = new ArrayList<MeCercanaContact>();
if (cursor.getCount() > 0)
{
while (cursor.moveToNext())
{
MyContact myContact = new MyContact();
String givenName = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
String postcode = cursor.getString(cursor.getColumnIndex(
ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
myContact.setFirstName(givenName);
myContact.setLastName(postcode);
contacts.add(myContact);
}
}
System.out.println(contacts.size());
解决方案
You are querying ContactsContract.Data, which is a generic container that holds a list of various contact details, such as phone numbers, postal codes etc.. You must filter the results for the rows whose ContactsContract.Data.MIMETYPE column equals StructuredPostal.CONTENT_ITEM_TYPE:
So change the query to:
Cursor cursor = cr.query(ContactsContract.Data.CONTENT_URI,
null, null, ContacsContract.Data.MIMETYPE + "='" +
ContactsContract.StructuredPostal.CONTENT_ITEM_TYPE + "'", null);
See ContactsContract.Data