views:

63

answers:

1

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());
+1  A: 

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

Thorstenvv