Search code examples
androidandroid-contactsphone-number

Reading contact phone numbers works for some and not others?


I am reading contact names and phone numbers from the contacts list in Android. I am reading the names successfully. However, when I go to look up a contact phone number by name (which are all unique in this case, it's just a test), it works perfectly for only one contact, gets no phone number for others, and gets the wrong phone number for one.

Here is the code in my getNumbers method:

private String getNumber(String name){
    String returnMe="";
    ContentResolver contentResolver = getContentResolver();
    Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null,
            "DISPLAY_NAME = '" + getIntent().getStringExtra("name") + "'", null, null);

    if(cursor.moveToFirst()){
        String identifier = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
        Cursor phones = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null, ContactsContract.CommonDataKinds.Phone._ID + " = " + identifier, null, null);
        while(phones.moveToNext()){
            returnMe = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            int type = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
            switch(type){
                case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
                    System.out.println("mobile number found"); break;
                default:
                    System.out.println("nothing found."); break;
            }
        }
    }
    return returnMe;
}

Solution

  • You're doing a few things wrong:

    1) The second query must target the Data table, not the Phone table:

    Cursor phones = contentResolver.query(ContactsContract.Data.CONTENT_URI, ...
    

    and specify that you want the Phone number in the DATA1 column in the where clause:

    Data.MIMETYPE = Phone.CONTENT_ITEM_TYPE
    

    2) You need to filter the results by the RawContact's _ID

    This compares the _ID of the Contact row with the _ID of the Phone row, which have very little chance to be the same:

    ContactsContract.CommonDataKinds.Phone._ID + " = " + identifier
    

    This compares the Data.CONTACT_ID with the cursor's Contact._ID property

    Data.CONTACT_ID + " = " + identifier
    

    The example on the Data javadoc page gives a more complete example:

    Finding all Data of a given type for a given contact

    Cursor c = getContentResolver().query(Data.CONTENT_URI,
          new String[] {Data._ID, Phone.NUMBER, Phone.TYPE, Phone.LABEL},
          Data.CONTACT_ID + "=?" + " AND "
                  + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'",
          new String[] {String.valueOf(contactId)}, null);