Android - back from Contacts intent without selecting one - android

In my android application I have a list of people (name and telephone number) and I let the user add a person to the app's database by importing one from their contacts list. Everything works fine, but a user could click the button to import a new person and then go back, so the Contacts intent will be closed without actually selecting a contact.
So I need to know where to put an if, or something else, in my code in order to see whether the user selected a contact or not.
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();
String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor cursor = getContentResolver().query(contactUri, null, null, null, null);
cursor.moveToFirst();
// Retrieve the name from the DISPLAY_NAME column
String name = cursor.getString(cursor.getColumnIndex(ontactsContract.Contacts.DISPLAY_NAME));
// Retrieve the phone number from the NUMBER column
int column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String number = cursor.getString(column);
// update database
dbManager.addPerson(name, number, true);
}
}
}
So how can I check if the user actually selected a contact or went back?

So I need to know where to put an if, or something else, in my code in order to see whether the user selected a contact or not.
You already have the code for this: if (resultCode == RESULT_OK). If the user presses BACK, you will not get RESULT_OK.

You are using an startActivityForResult which will return you back to the same activity once your
Intent.ACTION_PICK, Uri.parse("content://contacts")
jobs gets over that is the user has selected a contact.
And in order to get the name , number or any other details of the contact selected you do it in your onActivityResult callback like follows :
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if(reqCode == PICK_CONTACT_REQUEST) {
String cNumber = null;
String cName = null;
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor cursor = getContentResolver().query(contactData, null, null, null, null);
String hasPhone = null;
String contactId = null;
if (cursor != null) {
cursor.moveToFirst();
try {
hasPhone = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
} catch (IllegalArgumentException e) {
Log.e(TAG, "Exception Message : " + e.getMessage());
DisplayMessage.error("Sorry can't access contacts. Check permissions settings.", this);
return;
}
if (hasPhone != null && hasPhone.equals("1")) {
Cursor phones = getContentResolver().query
(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = " + contactId, null, null);
if (phones != null) {
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll("[-() ]", "");
cNumber = phoneNumber;
}
phones.close();
}
cName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.d(TAG, "Contact name is:" + cName);
}
cursor.close();
}
}
}
}

Related

Contacts aren't showing up on my edittext

So i've been trying to add contact to a edittext,i've used Onclickevent to invoke contacts and then once a contact has been selected,it should be written to edittext,but i'm not able to do that,below is my Onactivity 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 name = "";
try {
Uri result = data.getData();
//writeToFile("uri" +result);
String id = result.getLastPathSegment();
// query for name
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[] { id },
null);
if (cursor != null && cursor.moveToFirst())
{
int phoneIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA);
int nameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
writeToFile("ifcursor" +phoneIdx+nameIdx);
name = cursor.getString(nameIdx);
}
} catch (Exception e) {
//Log.e(DEBUG_TAG, "Failed to get name", e);
} finally {
if (cursor != null) {
cursor.close();
}
// phNo = (EditText) findViewById(R.id.phone_number);
phNo.setText(name);
if (name.length() == 0) {
Toast.makeText(getApplicationContext(),"Name not found for contact.",Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
//Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
any help would be deeply appreciated,it stucks on "name not found"
Try this one
#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.DISPLAY_NAME);
String number = cursor.getString(column);
phNo.setText(number );
// Do something with the phone number...
}
}
}
If you need the user to pick a contact with a phone number, you should call the following intent:
Intent i = new Intent(Intent.ACTION_PICK, Phone.CONTENT_URI);
startActivityForResult(i, CONTACT_PICKER_RESULT);
Then you can handle the response in onActivityResult like so:
Uri result = data.getData();
// because we asked for a Phone.CONTENT_URI picker, we'll get a uri for a Phone._ID entry
String id = result.getLastPathSegment();
String[] projection = new String[] { Phone.DISPLAY_NAME, Phone.NUMBER };
String selection = Phone._ID + "=" + id;
Cursor cursor = getContentResolver().query(Phone.CONTENT_URI, projection, selection,null, null);
if (cursor != null && cursor.moveToFirst()) {
String name = cursor.getString(0);
String number = cursor.getString(1);
Log.d("MyActivity", "got name=" + name + ", phone=" + number);
}
if (cursor != null) {
cursor.close();
}

How to get phone number type label from given phone number in android

I tried to print Contact name(Eg. "Jose") & Contact phone number type value(Eg. "Home","Work",etc.,) from phone contact for given particular phone number(Eg. "9600515852")
for this i used bellow code. but i can able get Contact name only. i am getting app crash when i am trying to get the phone number type.
Please guide me.
String number = getContactName(this, "9600515852");
Toast.makeText(getApplicationContext(),number,Toast.LENGTH_LONG).show();
private String getContactName(Context context, String number) {
String TAG ="" ;
String name = null, label=null;
int type=0;
// define the columns I want the query to return
String[] projection = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME,ContactsContract.PhoneLookup._ID };
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
// query time
Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null);
if(cursor != null) {
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
// type = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
} else {
Log.v(TAG, "Contact Not Found # " + number);
}
cursor.close();
}
return name+" - "+number;
}
use
name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
instead of
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
In My case, On button click getting contact information from Contacts app is like this. And it is working
Call an Intent
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);
Handle the result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
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);
if (c.moveToFirst()) {
String id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String resultedPhoneNum = pop.getContactNumber(id, MainActiv.this);
String resultedName=pop.getContactName(name, MainActiv.this);
contactName.setText(resultedName);
}
}
break;
}
}
Hope that helps!
Well the correct approach is to include the Phone.TYPE in your Projection query. It contains only DISPLAY_NAME andID and it crashes as there is no field as "type" included in your query.
This will definitely solve your issue.
Try this:
type = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.TYPE));

Accessing contacts list, searching for a contact, pulling its number and finally dial (android)

My app gets a contact name from the user, and then it is supposed to search in the contacts list if the contact exists. If it does, then pull its number and then automatically dial this number.
I can't seem to understand how to look for the contact name and then pull its number, if it exists.
public boolean seekAction(String s)
{
Intent callIntent= new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
callIntent.setType(Phone.CONTENT_TYPE);
if (callIntent.resolveActivity(getPackageManager()) != null)
{
startActivityForResult(callIntent, CONTACT_CALL_CODE_REQUEST);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode == RESULT_OK)
{
if(requestCode == CONTACT_CALL_CODE_REQUEST)
{
// Get the URI and query the content provider for the phone number
Uri contactUri = data.getData();
String[] s = new String[]{Phone.NUMBER};
Cursor cursor = getContentResolver().query(contactUri, s, null, null, null);
// If the cursor returned is valid, get the phone number
if (cursor != null && cursor.moveToFirst())
{
int numberIndex = cursor.getColumnIndex(Phone.NUMBER);
String number = cursor.getString(numberIndex);
// Do something with the phone number
Log.i("actionCallResult()", "phone number= "+number);
Intent intent = new Intent(Intent.ACTION_DIAL);//calling intent
intent.setData(Uri.parse("tel:" + number));
if (intent.resolveActivity(getPackageManager()) != null)
{
startActivity(intent);
}
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
I have this code, but it doesn't help me to look for the contact by its name.
edit:
public boolean actionCallResult(String str)
{
Log.i("actionCallResult()", "inside actionCallResult");
Cursor contacts = getContentResolver().query(Phone.CONTENT_URI, null, null, null, null);
boolean contactFound = false; // If the cursor returned is valid, get the phone number
if (contacts != null && contacts.moveToFirst())
{
do{
String contactName = contacts.getString(contacts.getColumnIndex(Phone.DISPLAY_NAME));
if (contactName.contains(str)) //contactName.equals(str)
{
contactFound = true;
break;
}
else
{
if(str.charAt(0)== 'ל')
{
if (contactName.contains(str.substring(1)))
{
contactFound = true;
break;
}
}
}
}while (contacts.moveToNext());
}
if(contactFound)
{
String number= contacts.getString(contacts.getColumnIndex(Phone.NUMBER));
Log.i("actionCallResult()", "phone number= "+number);
Intent intent = new Intent(Intent.ACTION_DIAL);//calling intent
intent.setData(Uri.parse("tel:" + number));
if (intent.resolveActivity(getPackageManager()) != null)
{
startActivity(intent);
}
}
contacts.close();
return contactFound;
}
I wrote a simple code that looks for a contact named "Mike Peterson" and toasts a message with the contact's number if found, and a "not found" message otherwise.
This code is raw and by no means should serve any professional implementations. A better approach would be to use custom AsyncTasks and Array Storage.
Please note that this following permission declaration must appear in your manifest:
<uses-permission android:name="android.permission.READ_CONTACTS" />
The following was tested under a simple main activity:
String str = "Mike Peterson"; // As an example
Cursor contacts = getApplicationContext().getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
boolean contactFound = false;
while (contacts.moveToNext()) {
String contactName =
contacts.getString(contacts.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if (contactName.equals(str)) {
contactFound = true;
break;
}
}
Toast.makeText(getApplicationContext(), contactFound ?
contacts.getString(contacts.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.NUMBER)) : "Contact not found!"
, Toast.LENGTH_LONG).show();
contacts.close();

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.

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