Selecting a number from user with multiple numbers when using the contact picker

Kevin picture Kevin · May 30, 2011 · Viewed 8.1k times · Source

I'm trying to allow a user to select a phone number from a contact using the contact picker. However, right now all the examples I see online show how you can select a contact, but I am hoping to have a second screen then pop up if that contact has multiple phone numbers so you can specify which one you want to select (the way that text message lets you do so when you select a contact).

My question is, do you have to gather all of the numbers and then ask the user to select a number, or is this functionality already built into Android? I'm hoping I just forgot a flag or something.

Answer

howettl picture howettl · Jul 5, 2011

Alternatively, you can initially display the phone numbers associated with each contact in the Contact Picker and select one that way. Launch contact picker this way (note the different URI than my other answer):

Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, REQUEST_PICK_CONTACT);

Then, in onActivityResult():

Uri result = data.getData();
Log.v(TAG, "Got a result: " + result.toString());

// get the phone number id from the Uri
String id = result.getLastPathSegment();

// query the phone numbers for the selected phone number id
Cursor c = getContentResolver().query(
    Phone.CONTENT_URI, null,
    Phone._ID + "=?",
    new String[]{id}, null);

int phoneIdx = c.getColumnIndex(Phone.NUMBER);

if(c.getCount() == 1) { // contact has a single phone number
    // get the only phone number
    if(c.moveToFirst()) {
        phone = c.getString(phoneIdx);
        Log.v(TAG, "Got phone number: " + phone);

        loadContactInfo(phone); // do something with the phone number

    } else {
        Log.w(TAG, "No results");
    }
}