Search code examples
androidcontactscontract

Retrieve all numbers from one contact issue


I know this is a common question since I found many answers about it, but I still have an issue regarding phone number retrieving.

I want to get ALL numbers from one contact picked from the PICK_CONTACT activity.

Here is my code from the onActivityResult() block

 @Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
    super.onActivityResult(reqCode, resultCode, data);

    switch (reqCode) {
        case (PICK_CONTACT) :
            if (resultCode == Activity.RESULT_OK) {

                ArrayList<String> allContacts = new ArrayList<String>();

                Uri contactData = data.getData();
                Cursor c =  getContentResolver().query(contactData, null, null, null, null);
                while (c.moveToNext()) {

                    String contact_id = c.getString(c.getColumnIndex( _ID ));
                    String hasPhone =c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

                    if (hasPhone.equalsIgnoreCase("1")) {
                        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { contact_id }, null);
                        while (phones.moveToNext())
                        {
                            String contactNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            allContacts.add(contactNumber);

                            break;
                        }
                        phones.close();

                    }
                    String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    TXT_EmergencyContactNameProfile.setText(name);
                }

            }
            break;
    }
}

I expected the loop while (phones.moveToNext()) to get all different numbers ... but no

Thank you very much in advance ;)


Solution

  • Try to delete the "break;" inside the while loop.