First, you may need to query all contact in phone book.
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME
};
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
// Build adapter with contact entries
Cursor mCursor = managedQuery(uri, projection, selection, selectionArgs, sortOrder);
//
// Bind mCursor to to your Listview
//
After that, when user select a contact in your list view, you make a second query to get label and number of that contact.
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
mCursor.moveToPosition(position);
startManagingCursor(mCursor);
String contactID = mCursor.getString(mCursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor phoneNumCursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone.CONTACT_ID + "=?", new String[] { contactID }, null);
phoneNumCursor.moveToFirst();
Vector<String> phoneTypeList = new Vector<String>();
Vector<String> phoneNumberList = new Vector<String>();
while (!phoneNumCursor.isAfterLast()){
int type = phoneNumCursor.getInt(phoneNumCursor.getColumnIndex(Phone.TYPE));
phoneTypeList.add(String.valueOf(Phone.getTypeLabel(getResources(),type,"")));
phoneNumberList.add(phoneNumCursor.getString(phoneNumCursor.getColumnIndex(Phone.NUMBER)));
phoneNumCursor.moveToNext();
}
//
// Feel free to show label and phone number of that contact. ^^
//
Updated:
Below is an example if you want to use Contact Picker.
private static final int CONTACT_PICKER_RESULT = 1001;
protected void startContactPicker(){
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String phoneNumber = "";
try {
Uri result = data.getData();
String id = result.getLastPathSegment();
cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone.CONTACT_ID + "=?", new String[] { id }, null);
int phoneIdx = cursor.getColumnIndex(Phone.DATA);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()){
phoneNumber = cursor.getString(phoneIdx);
//
// this will go through all phoneNumber of selected contact.
//
cursor.moveToNext();
}
}
} catch (Exception e) {
} finally {
if (cursor != null) {
cursor.close();
}
numberView.setText(phoneNumber);
}
break;
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…