I'm using the old Contacts API to choose a contact with a phone number. I want to use the newer ContactsContracts API. I want...
- ...a dialog shown with all contacts that have phone numbers.
- ...the user to choose a contact AND one of their phone numbers.
- ...access to the chosen phone number.
The ContactsContracts is very complicated. I found many examples, but none that fit my needs. I don't want to choose a contact and then query for the contact's details because this will give me a list of their phone numbers. I need the user to choose ONE of the contact's phone numbers. I don't want to have to write my own dialogs to display the contacts or to have the user pick a phone number. Is there any simple way to get what I want?
Here is the old API code I'm using:
static public final int CONTACT = 0;
...
Intent intent = new Intent(Intent.ACTION_PICK, Contacts.Phones.CONTENT_URI);
startActivityForResult(intent, CONTACT);
...
public void onActivityResult (int requestCode, int resultCode, Intent intent) {
if (resultCode != Activity.RESULT_OK || requestCode != CONTACT) return;
Cursor c = managedQuery(intent.getData(), null, null, null, null);
if (c.moveToFirst()) {
String phone = c.getString(c.getColumnIndexOrThrow(Contacts.Phones.NUMBER));
// yay
}
}
Here you can find a great code from : http://developer.android.com/training/basics/intents/result.html
From the older answers and my own tests I ended using this:
launching contact list:
...
...
onActivityResult handler:
So what are the differences from Rizvan answer?
On my testing device (Samsung S3):
READ_CONTACS
permission (because I use the returneduri
as is, when I use only the "id" of it and create select ID=? query type, the permission crash happens)uri
which leads directly to that single selected numberuri
to multiple numbers, the proposed onActivityResult handler can be extended to read them all and you can do your own selection dialog.So this looks to me like perfect fit for what OP asked.
Now I just wonder:
READ_CONTACTS
permission (it should not, according to http://developer.android.com/guide/topics/providers/content-provider-basics.html#Intents )Let me know if you have real world experience with it, thanks.
Update: HTC Desire S, custom rom with android 4.0.3 -> has both problems, requires READ_CONTACTS permission to work, and will return multiple numbers without additional selection dialog.
This code might help you. I think the PICK action only returns the ID of the contact picked. From that you could query the Contact provider and if there are multiple phone numbers, prompt the user to select one of them.
You can use this too (updated):
Updated 28/12 -2011
You can use this:
You need to adapt this to work with your app.
I find one way to pick exactly the phone number from contact list. Below is the snippet.
1.Launch contacts to select phone numbers in fragment.
2.Pick the selected phone numbers in fragment.
P.S.
private final int PICK_CONTACT = 666;