开发者

Android; I only have 2 contacts, yet I can obtain 5 from a query, why?

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 inst开发者_StackOverflow社区ead 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());


After API 21 We Write this Query for remove contact duplicacy.

String select = ContactsContract.Data.HAS_PHONE_NUMBER + " != 0 AND " + 
ContactsContract.Data.MIMETYPE
                + " = " + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + " 
AND "+ ContactsContract.Data.RAW_CONTACT_ID + " = " + 
ContactsContract.Data.NAME_RAW_CONTACT_ID;

Cursor cursor = mContent.query(ContactsContract.Data.CONTENT_URI, null, select, 
 null, null);


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


a contact that is registered to multiple groups will show up multiple times if you query the Uri CONTENT_URI = ContactsContract.Data.CONTENT_URI

Add this to your SELECTION:

 + ContactsContract.Data.DATA1 + " = 1 " ;  //show only contacts in group 1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜