I used Android Essentials: Using the Contact Picker
It presents a working example for selecting an email address.
The key code, after using the contact picker to get a contact ID, is this:
// query for everything email
cursor = getContentResolver().query(
Email.CONTENT_URI, null,
Email.CONTACT_ID + "=?",
new String[]{id}, null);
Where id
is the contact ID returned from the Contacts picker (as explained in the tutorial). To get the phone data, you will need to change this to:
// query for everything phone
cursor = getContentResolver().query(
Phone.CONTENT_URI, null,
Phone.CONTACT_ID + "=?",
new String[]{id}, null);
Be aware that a contact can have multiple phone numbers, so you will have to build a second dialog to select a particular phone number.
ArrayList<String> phoneNumbers = new ArrayList<String>();
String name = "";
String number = "";
int nameIdx = cursor.getColumnIndex(Phone.DISPLAY_NAME);
int numberIdx = cursor.getColumnIndex(Phone.DATA);
// Get all phone numbers for the person
if (cursor.getCount() > 0) {
cursor.moveToFirst();
do {
name = cursor.getString(nameIdx); // get the name from the cursor
number = cursor.getString(numberIdx); // get the phone number from the cursor
phoneNumbers.add(number);
Log.v(DEBUG_TAG, "Got name: " + name + " phone: "
+ number);
} while (cursor.moveToNext());
showPhoneNumberSelectionDialog(name,phoneNumbers);
} else {
Log.w(DEBUG_TAG, "No results");
}
(or you can adapt the cursor reading from the above code as needed)
private void showPhoneNumberSelectionDialog(String name,
final ArrayList<String> phoneNumbers) {
1. Build an AlertDialog to pick a number from phoneNumbers (with'name' in the title);
2. Send an SMS to the number
}
Building the alert dialog is not hard, but involves transforming the ArrayList into a String array. See Convert ArrayList to String []
Sending the SMS is reasonably easy. There are plenty of examples on the web.
This SO Q&A (How to read contacts on Android 2.0) is also good background, but in the end I didn't use any code from it.