search contacts and get the contact number from phone contacts in android - android

I am working with an app, in this I have to search contacts when the button click and select one of the contact from phone contacts. Finally I want to set it to edittext.I can able to search the contacts from phone contacts but I am unable to get contact from phone contacts.
activity:
searchBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent,1);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==RESULT_OK){
Uri contactData = data.getData();
Cursor cursor = managedQuery(contactData, null, null, null, null);
cursor.moveToFirst();
String number = cursor.getString(cursor.getColumnIndexOrThrow
(ContactsContract.CommonDataKinds.Phone.NUMBER));
//contactName.setText(name);
ephoneNumber.setText(number);
//contactEmail.setText(email);
}
}

First set Intent for StartActivityForResult Like this
private void pickContact() {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
then deal with result what intent carry from native contact application
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request it is that we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Get the URI that points to the selected contact
Uri contactUri = data.getData();
// We only need the NUMBER column, because there will be only one row in the result
String[] projection = {Phone.NUMBER};
// Perform the query on the contact to get the NUMBER column
// We don't need a selection or sort order (there's only one result for the given URI)
// CAUTION: The query() method should be called from a separate thread to avoid blocking
// your app's UI thread. (For simplicity of the sample, this code doesn't do that.)
// Consider using CursorLoader to perform the query.
Cursor cursor = getContentResolver()
.query(contactUri, projection, null, null, null);
cursor.moveToFirst();
// Retrieve the phone number from the NUMBER column
int column = cursor.getColumnIndex(Phone.NUMBER);
String number = cursor.getString(column);
// Do something with the phone number...
}
}
}
see another reference links
Link 1
Link 2

Bharat,
You need permission like -
android:name="android.permission.READ_CONTACTS"/>
Then, Calling the Contact Picker
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
Then,
#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) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndexOrThrow(People.NAME));
// TODO Whatever you want to do with the selected contact name.
}
}
break;
}
}
OR, In other way You can use
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(Phone.CONTENT_URI, null, null, null, null);
int contactIdIdx = cursor.getColumnIndex(Phone._ID);
int nameIdx = cursor.getColumnIndex(Phone.DISPLAY_NAME);
int phoneNumberIdx = cursor.getColumnIndex(Phone.NUMBER);
int photoIdIdx = cursor.getColumnIndex(Phone.PHOTO_ID);
cursor.moveToFirst();
do {
String idContact = cursor.getString(contactIdIdx);
String name = cursor.getString(nameIdx);
String phoneNumber = cursor.getString(phoneNumberIdx);
//...
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
Above solution is simple and working for contact number fetching.

try this
CursorLoader cursorLoader = new CursorLoader(mActivity,
CallLog.Calls.CONTENT_URI, null, null, null, null);
managedCursor = cursorLoader.loadInBackground();
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int name = managedCursor.getColumnIndex(CallLog.Calls.CACHED_NAME);
String conTactnumber=managedCursor.getString(number);
String contactname=managedCursor.getString(name);
set permission
<uses-permission android:name="android.permission.READ_CONTACTS" >
</uses-permission>

Related

Pass phone number as destination of my message

Am trying to pass the phone number I picked from contact list of my device. I have edittext to write my message and then by one click I want to pick a number from the list and send at same time. Access phone number is confusing to me rather than access the name itself.( I don't need the name, i want to send my message to him/her as they have phone number.) I'm having java.lang.IllegalArgumentException: Invalid destinationAddress for sms.sendTextMessage**
public void Send(View view){
String myMsg = myMessage.getText().toString();
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(no,null,myMsg,null,null);//"8044842795
}
String no = "";
#Override
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(reqCode, resultCode, data);
if(reqCode == PICK_CONTACT) {
if(resultCode == ActionBarActivity.RESULT_OK) {
Uri contactData = data.getData();
Cursor cur = getContentResolver().query(contactData, null, null, null, null);
ContentResolver contect_resolver = getContentResolver();
if (cur.moveToFirst()) {
String id = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
Cursor phoneCur = contect_resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
if (phoneCur.moveToFirst()) {
no = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
}
}
}
}
You need to send the SMS in onActivityResult. Until that is called, you don't know who was chosen so you can't get their number.

Fetching a Single Phone Number from a contact in Contacts Book which is having multiple numbers saved

I need to ask a user for a contact number to make a call. On Button Click the User should be directly redirected to Contacts Book and the user can select a Phone Number. Following is the Source Code what I am using now.
Button buttonReadContact;
TextView textPhone;
final int RQS_PICKCONTACT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonReadContact = (Button)findViewById(R.id.readcontact);
textPhone = (TextView)findViewById(R.id.phone);
buttonReadContact.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
//Start activity to get contact
final Uri uriContact = ContactsContract.Contacts.CONTENT_URI;
Intent intentPickContact = new Intent(Intent.ACTION_PICK, uriContact);
startActivityForResult(intentPickContact, RQS_PICKCONTACT);
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(resultCode == RESULT_OK){
if(requestCode == RQS_PICKCONTACT){
Uri returnUri = data.getData();
Cursor cursor = getContentResolver().query(returnUri, null, null, null, null);
if(cursor.moveToNext()){
int columnIndex_ID = cursor.getColumnIndex(ContactsContract.Contacts._ID);
String contactID = cursor.getString(columnIndex_ID);
int columnIndex_HASPHONENUMBER = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
String stringHasPhoneNumber = cursor.getString(columnIndex_HASPHONENUMBER);
if(stringHasPhoneNumber.equalsIgnoreCase("1")){
Cursor cursorNum = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactID,
null,
null);
//Get the first phone number
if(cursorNum.moveToNext()){
int columnIndex_number = cursorNum.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String stringNumber = cursorNum.getString(columnIndex_number);
textPhone.setText(stringNumber);
}
}else{
textPhone.setText("NO Phone Number");
}
}else{
Toast.makeText(getApplicationContext(), "NO data!", Toast.LENGTH_LONG).show();
}
}
}
}
But now the issue is I can only select one number from a contact which is having multiple Phone Numbers saved.
I need to do this as in Skype Application. When the User select a contact which is having multiple contacts, from the Contacts Book itself it should ask the User to choose the number. Please help me to do it.
I used this code to open the Contacts and allow the user to select a single contact, then parse the result to display the contact name, phone number and thumbnail photo. In the example below, the members mName, mPhoneNumber, and mContactImage are already defined.
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Start an activity to pick a single contact (ACTION_PICK)
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
// Show only contacts with phone numbers
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
// Start the Contacts activity
startActivityForResult(intent, PICK_CONTACT);
}
});
Parse the results in onActivityResult().
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case PICK_CONTACT :
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
String[] projection = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Photo.PHOTO_THUMBNAIL_URI};
Cursor c = getActivity().getContentResolver().query(contactData, projection, null, null, null);
c.moveToFirst();
int nameIdx = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int phoneNumberIdx = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int photoIdx = c.getColumnIndex(ContactsContract.CommonDataKinds.Photo.PHOTO_THUMBNAIL_URI);
String name = c.getString(nameIdx);
String phoneNumber = c.getString(phoneNumberIdx);
String photo = c.getString(photoIdx);
if (photo == null) {
// If no photo then substitute a dummy image
mContactImage.setImageResource(R.drawable.ic_contact_picture);
} else {
// Display the contact photo
final Uri imageUri = Uri.parse(photo);
mContactImage.setImageURI(imageUri);
}
if (name == null) {
name = "No Name";
}
mName.setText(name);
mPhoneNumber.setText(phoneNumber);
c.close();
// Now you have the phone number
}
break;
}
}
I think this answers your question.

Getting Contacts numbers

I am having problem getting the number of contact that i have selected. In my app I call the built in application for contacts as a new activity, when you choose a contact the activity returns his name, now I need it to return all the numbers that the user entered for that contact. I found the code in some tutorial on the internet... Here is the code
This is how i call the contact activity
mSuspectButton = (Button) v.findViewById(R.id.crime_suspect);
mSuspectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(i, REQUEST_CONTACT);
}
});
This is how i get the name of the selected contact:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK)
return;
if (requestCode == REQUEST_CONTACT) {
Uri contactUri = data.getData();
// Specify which fields you want your query to return
// values for.
String[] queryFields = new String[] {
ContactsContract.Contacts.DISPLAY_NAME };
// Perform your query - the contactUri is like a "where"
// clause here
Cursor c = getActivity().getContentResolver().query(contactUri,
queryFields, null, null, null);
// Double-check that you actually got results
if (c.getCount() == 0) {
c.close();
return;
}
// Pull out the first column of the first row of data -
// that is your suspect's name.
c.moveToFirst();
String suspect = c.getString(0);
mCrime.setSuspect(suspect);
mSuspectButton.setText(suspect);
c.close();
}
}
So please can anyone help, I really don't understand how these works?
Use this in your onActivityResult, this will return you the selected number
#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){
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()){
String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._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 +" = "+ id,null, null);
phones.moveToFirst();
String cNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
}
}
}
}
1) Write this code to fetch all contact numbers and names.
2) Add them in separate arraylists.
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll(" ", "");
alContactNames.add(name);
alContactNumbers.add(phoneNumber);
}
phones.close();
3) make listview in your app with custom adapter. In each list item, there needs to be the contact number , contact name and check box for selection.
this will solve your problem.

geting force close when selecting google contacts

hi I am working on an app that sends SMS to selected contact.
to select a contact I am using this code
public void selectRecipient(View V)
{
Intent pickContactIntent=new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(pickContactIntent,1);
}
My onActivityResult function is following
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK)
{
if(requestCode==1)
{
count++;
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
c.moveToFirst();
name= c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String id = c.getString(c.getColumnIndex(Contacts._ID));
Cursor cur =getContentResolver().query(CommonDataKinds.Phone.CONTENT_URI, null, CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null);
cur.moveToNext();
String phoneNumber = cur.getString(cur.getColumnIndex(CommonDataKinds.Phone.NUMBER));
}
}
}
when I select any google contact in contact list, I get force close.
If I select a phone contact that has anumber then it's working fine.
What should I do to rectify this?
you will need to Check Current contact has at least one phone number Using ContactsContract.Contacts.HAS_PHONE_NUMBER and Close Cursor using Cursor.close(); After Getting Phone Number . So Change your Code as:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
case (1) :
{
if (resultCode == Activity.RESULT_OK)
{
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
c.moveToFirst();
String phoneNumber=this.getContactPhone(c);
}
break;
}
}
}
private String getContactPhone(Cursor cursor)
{
int phoneColumn = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
int phoneNum = cursor.getInt(phoneColumn);
String phoneResult="";
//System.out.print(phoneNum);
if (phoneNum > 0)
{
int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);
String contactId = cursor.getString(idColumn);
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = " + contactId,
null, null);
//int phoneCount = phones.getCount();
//allPhoneNum = new ArrayList<String>(phoneCount);
if (phones.moveToFirst())
{
for (;!phones.isAfterLast();phones.moveToNext())
{
int index = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int typeindex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
int phone_type = phones.getInt(typeindex);
String phoneNumber = phones.getString(index);
switch(phone_type)
{
case 2:
phoneResult=phoneNumber;
break;
}
//allPhoneNum.add(phoneNumber);
}
if (!phones.isClosed())
{
phones.close();
}
}
}
return phoneResult;
}
and Make Sure you have following permission in AndroidManifest.xml .
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />

How can I choose a phone number with Android's contacts dialog

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
}
}
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
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):
public void readcontact(){
try {
Intent intent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts/people"));
startActivityForResult(intent, PICK_CONTACT);
} catch (Exception e) {
e.printStackTrace();
}
}
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT) :
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
startManagingCursor(c);
if (c.moveToFirst()) {
String name = c.getString(c.getColumnIndexOrThrow(People.NAME));
String number = c.getString(c.getColumnIndexOrThrow(People.NUMBER));
personname.setText(name);
Toast.makeText(this, name + " has number " + number, Toast.LENGTH_LONG).show();
}
}
break;
}
}
Updated 28/12 -2011
You can use this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
final EditText phoneInput = (EditText) findViewById(R.id.phoneNumberInput);
Cursor cursor = null;
String phoneNumber = "";
List<String> allNumbers = new ArrayList<String>();
int phoneIdx = 0;
try {
Uri result = data.getData();
String id = result.getLastPathSegment();
cursor = getContentResolver().query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + "=?", new String[] { id }, null);
phoneIdx = cursor.getColumnIndex(Phone.DATA);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
phoneNumber = cursor.getString(phoneIdx);
allNumbers.add(phoneNumber);
cursor.moveToNext();
}
} else {
//no results actions
}
} catch (Exception e) {
//error actions
} finally {
if (cursor != null) {
cursor.close();
}
final CharSequence[] items = allNumbers.toArray(new String[allNumbers.size()]);
AlertDialog.Builder builder = new AlertDialog.Builder(your_class.this);
builder.setTitle("Choose a number");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String selectedNumber = items[item].toString();
selectedNumber = selectedNumber.replace("-", "");
phoneInput.setText(selectedNumber);
}
});
AlertDialog alert = builder.create();
if(allNumbers.size() > 1) {
alert.show();
} else {
String selectedNumber = phoneNumber.toString();
selectedNumber = selectedNumber.replace("-", "");
phoneInput.setText(selectedNumber);
}
if (phoneNumber.length() == 0) {
//no numbers found actions
}
}
break;
}
} else {
//activity result error actions
}
}
You need to adapt this to work with your app.
Here you can find a great code from : http://developer.android.com/training/basics/intents/result.html
static final int PICK_CONTACT_REQUEST = 1; // The request code
...
private void pickContact() {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request it is that we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Get the URI that points to the selected contact
Uri contactUri = data.getData();
// We only need the NUMBER column, because there will be only one row in the result
String[] projection = {Phone.NUMBER};
// Perform the query on the contact to get the NUMBER column
// We don't need a selection or sort order (there's only one result for the given URI)
// CAUTION: The query() method should be called from a separate thread to avoid blocking
// your app's UI thread. (For simplicity of the sample, this code doesn't do that.)
// Consider using CursorLoader to perform the query.
Cursor cursor = getContentResolver()
.query(contactUri, projection, null, null, null);
cursor.moveToFirst();
// Retrieve the phone number from the NUMBER column
int column = cursor.getColumnIndex(Phone.NUMBER);
String number = cursor.getString(column);
// Do something with the phone number...
}
}
}
From the older answers and my own tests I ended using this:
launching contact list:
import android.content.Intent;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
...
public static final int PICK_CONTACT = 100;
...
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
intent.setType(Phone.CONTENT_TYPE); //should filter only contacts with phone numbers
startActivityForResult(intent, PICK_CONTACT);
onActivityResult handler:
private static final String[] phoneProjection = new String[] { Phone.DATA };
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (PICK_CONTACT != requestCode || RESULT_OK != resultCode) return;
Uri contactUri = data.getData();
if (null == contactUri) return;
//no tampering with Uri makes this to work without READ_CONTACTS permission
Cursor cursor = getContentResolver().query(contactUri, phoneProjection, null, null, null);
if (null == cursor) return;
try {
while (cursor.moveToNext()) {
String number = cursor.getString(0);
// ... use "number" as you wish
}
} finally {
cursor.close();
}
// "cursor" is closed here already
}
So what are the differences from Rizvan answer?
On my testing device (Samsung S3):
the app does NOT need READ_CONTACS permission (because I use the returned uri as is, when I use only the "id" of it and create select ID=? query type, the permission crash happens)
when contact has multiple phone numbers, the picker itself does show dialog to select only one of them, then it returns uri which leads directly to that single selected number
even if some phone would return uri 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:
on which phones this will require the READ_CONTACTS permission (it should not, according to http://developer.android.com/guide/topics/providers/content-provider-basics.html#Intents )
on which phones it will return multiple numbers instead of doing the selection dialog
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.
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.
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
// filter the contacts with phone number only
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
2.Pick the selected phone numbers in fragment.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor cur = getActivity().getContentResolver().query(contactData, null, null, null, null);
if (cur == null) return;
try {
if (cur.moveToFirst()) {
int phoneIndex = cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
mobileNoEditText.setText(cur.getString(phoneIndex));
}
}
finally {
cur.close();
}
}
}
}
P.S. private final int PICK_CONTACT = 666;

Categories

Resources