I was able to successfully launch the contact picker and then set an editText in my activity to the phone number of the selected contact. What I'm trying to do now is to set two other editTexts to the first name and last name, respectively. I added the other editTexts and tried to retrieve the last and first name.
Here's what I have:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String number = "";
String lastName = "";
String firstName = "";
try {
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: "
+ result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for phone number
cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone.CONTACT_ID + "=?", new String[] { id },
null);
int phoneIdx = cursor.getColumnIndex(Phone.DATA);
int lastNameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds
.StructuredName.FAMILY_NAME);
int firstNameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds
.StructuredName.GIVEN_NAME);
// get the phone number
if (cursor.moveToFirst()) {
number = cursor.getString(phoneIdx);
lastName = cursor.getString(lastNameIdx);
firstName = cursor.getString(firstNameIdx);
Log.v(DEBUG_TAG, "Got number " + number);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to get phone number data", e);
} finally {
if (cursor != null) {
cursor.close();
}
EditText phoneNumberEditText = (EditText) findViewById(R.id.number);
phoneNumberEditText.setText(number);
EditText lastNameEditText = (EditText)findViewById(R.id.last_name);
lastNameEditText.setText(lastName);
EditText firstNameEditText = (EditText)findViewById(R.id.first_name);
firstNameEditText.setText(firstName);
if (number.length() == 0) {
Toast.makeText(this, "No phone number found for this contact.",
Toast.LENGTH_LONG).show();
}
if(lastName.length()==0) {
Toast.makeText(this, "No last name found for this contact.",
Toast.LENGTH_LONG).show();
}
if(firstName.length()==0) {
Toast.makeText(this, "No first name found for this contact.",
Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
I must be missing something basic. Any thoughts?
Try this:
String lastName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME))
If you call a managedQuery it will return the contacts full name and the id but no phone number.
Cursor cursor = managedQuery(intent.getData(), null, null, null, null);
cursor.moveToNext(); String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name=cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
Related
I let the user choose email from contacts with following intent:
Intent emailPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Email.CONTENT_URI);
startActivityForResult(emailPickerIntent, Constants.CONTACT_PICKER_RESULT);
How can I query for the email the user chose in onActivityResult method?
Following code will help you to get the email address onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
switch (requestCode)
{
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String email = "", name = "";
try {
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: " + result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for everything email
cursor = getContentResolver().query(Email.CONTENT_URI, null, Email._ID + "=" + id, null, null);
int nameId = cursor.getColumnIndex(Contacts.DISPLAY_NAME);
int emailIdx = cursor.getColumnIndex(Email.DATA);
// let's just get the first email
if (cursor.moveToFirst()) {
email = cursor.getString(emailIdx);
name = cursor.getString(nameId);
Log.v(DEBUG_TAG, "Got email: " + email);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to get email data", e);
} finally {
if (cursor != null) {
cursor.close();
}
EditText emailEntry = (EditText) findViewById(R.id.editTextv);
EditText personEntry = (EditText) findViewById(R.id.person);
emailEntry.setText(email);
personEntry.setText(name);
if (email.length() == 0 && name.length() == 0)
{
Toast.makeText(this, "No Email for Selected Contact",Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
}
You also have to add following permission in your manifest file:
<uses-permission android:name="android.permission.READ_CONTACTS"/>
This question already has answers here:
Getting a Photo from a Contact
(9 answers)
Closed 8 months ago.
With my present code I am getting only the contact number. But I want to get contact's name and contact's photo path. Have tried many codes by googling, but I am not able to get it done. Tried this too, but got FileNotFoundException. Can someone please help me achieve that by adding code snippets to the below code?
public void getContact(View view)
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);
}
protected void onActivityResult(int requestCode, int resultCode,Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK && requestCode == 1)
{
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String phoneNumber = c.getString(0);
int type = c.getInt(1);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
}
This code traverses all contacts and gets their first name, last name and photo as a bitmap:
Cursor cursor = App
.getInstance()
.getContentResolver()
.query(ContactsContract.Contacts.CONTENT_URI, null, null, null,
null);
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
long id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts._ID));
// get firstName & lastName
Cursor nameCur = App.getInstance().getContentResolver()
.query(ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.MIMETYPE
+ " = ? AND "
+ StructuredName.CONTACT_ID
+ " = ?",
new String[] {
StructuredName.CONTENT_ITEM_TYPE,
Long.valueOf(id).toString() }, null);
if (nameCur != null) {
if (nameCur.moveToFirst()) {
String displayName = nameCur.getString(nameCur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (displayName == null) displayName = "";
String firstName = nameCur.getString(nameCur.getColumnIndex(StructuredName.GIVEN_NAME));
if (firstName == null) firstName = "";
Log.d("--> ", firstName.length()>0?firstName:displayName);
String middleName = nameCur.getString(nameCur.getColumnIndex(StructuredName.MIDDLE_NAME));
if (middleName == null) middleName = "";
String lastName = nameCur.getString(nameCur.getColumnIndex(StructuredName.FAMILY_NAME));
if (lastName == null) lastName = "";
lastName = middleName + (middleName.length()>0?" ":"") + lastName;
Log.d("--> ", lastName);
}
nameCur.close();
}
Bitmap photo = null;
try {
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(App.getContext().getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.valueOf(id)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
}
if (inputStream != null) inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("--> ", photo);
}
}
if (cursor != null) { cursor.close(); }
You also needs this permission: <uses-permission android:name="android.permission.READ_CONTACTS" />
Hope that helps!
This is the method am using to get contact photo, number and name but am dong this from a Fragment.
1 Set the permission in your manifest.
<uses-permission android:name="android.permission.READ_CONTACTS" />
2 Declare a constant:
private static final int REQUEST_CODE_PICK_CONTACT = 1;
3 In my app the user is required to choose a phone contact by clicking on a button. So in the onClick() method I do this:
contactChooserButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI), REQUEST_CODE_PICK_CONTACT);
}
});
4 Add the methods to retrieve photo, name, and number:
private String retrieveContactNumber() {
String contactNumber = null;
// getting contacts ID
Cursor cursorID = getActivity().getContentResolver().query(uriContact,
new String[]{ContactsContract.Contacts._ID},
null, null, null);
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
}
cursorID.close();
Log.e(TAG, "Contact ID: " + contactID);
// Using the contact ID now we will get contact phone number
Cursor cursorPhone = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{contactID},
null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneNumber = contactNumber;
}
cursorPhone.close();
Log.e(TAG, "Contact Phone Number: " + contactNumber);
return contactNumber;
}
//Retrieve name
private void retrieveContactName() {
String contactName = null;
// querying contact data store
Cursor cursor = getActivity().getContentResolver().query(uriContact, null, null, null, null);
if (cursor.moveToFirst()) {
// DISPLAY_NAME = The display name for the contact.
// HAS_PHONE_NUMBER = An indicator of whether this contact has at least one phone number.
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
personName = contactName;
}
cursor.close();
Log.e(TAG, "Contact Name: " + contactName);
}
//Retrieve photo (this method gets a large photo, for thumbnail follow the link below)
public void retrieveContactPhoto() {
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contactID));
Uri displayPhotoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
try {
AssetFileDescriptor fd =
getActivity().getContentResolver().openAssetFileDescriptor(displayPhotoUri, "r");
photoAsBitmap = BitmapFactory.decodeStream(fd.createInputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
finally, in your onActivityForResult method, do this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if(requestCode == REQUEST_CODE_PICK_CONTACT && resultCode == Activity.RESULT_OK) {
Log.e(TAG, "Response: " + data.toString());
uriContact = data.getData();
personPhoneTextField.setText(retrieveContactNumber());
//the method retrieveContactNumber returns the contact number,
//so am displaying this number in my EditText after getting it.
//Make your other methods return data of
//their respective types (Bitmap for photo)
retrieveContactPhoto();
retrieveContactName();
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
That's it.For Activities, take a look at this Android: Get Contact Details (ID, Name, Phone, Photo) on Github
I am new to android ,I need to get the details of my contacts, but the details include only 3
Contact name
contact number and
Email ID
when I press a Button it will show these 3 details of my all contacts
I am using android Eclair version 2.1. Any solution ?
By below code you can do that -
public void doLaunchContactPicker(View view) {
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 email = "", name = "";
try {
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: " + result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for everything email
cursor = getContentResolver().query(Email.CONTENT_URI, null, Email.CONTACT_ID + "=?", new String[] { id }, null);
int nameId = cursor.getColumnIndex(Contacts.DISPLAY_NAME);
int emailIdx = cursor.getColumnIndex(Email.DATA);
// let's just get the first email
if (cursor.moveToFirst()) {
email = cursor.getString(emailIdx);
name = cursor.getString(nameId);
Log.v(DEBUG_TAG, "Got email: " + email);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to get email data", e);
} finally {
if (cursor != null) {
cursor.close();
}
EditText emailEntry = (EditText) findViewById(R.id.editTextv);
EditText personEntry = (EditText) findViewById(R.id.person);
emailEntry.setText(email);
personEntry.setText(name);
if (email.length() == 0 && name.length() == 0)
{
Toast.makeText(this, "No Email for Selected Contact",Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
And, also refer these links -
Get Contact Details
How to Read Contacts
Get All Contact Details
Don't forget to add the required permission -
<uses-permission android:name="android.permission.READ_CONTACTS"/>
in your AndroidManifest.xml file. And, Just modify this code with your needs.
You can access addressbook like this;
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,null, null,ContactsContract.Contacts.DISPLAY_NAME);
int kisiSayisi = cur.getCount();
if(kisiSayisi > 0)
{
int KisiIndex = 0;
while(cur.moveToNext())
{
String id = cur.getString(cur.getColumnIndex(BaseColumns._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?", new String[] { id }, null);
while (pCur.moveToNext())
{
String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
//String phoneType = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
String dogruGSM = gsmNoKontrol(phone);
if(dogruGSM.compareTo("0") != 0){
Kisi kisi = new Kisi(KisiIndex, name, dogruGSM, false);
MyList.add(kisi);
KisiIndex ++;
}
}
pCur.close();
}
}
}
Im having some trouble with getting a phone number from a contact using the ContactsContract
My code is
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String phone = "";
try {
Bundle extras = data.getExtras();
Set<String> keys = extras.keySet();
Iterator<String> iterate = keys.iterator();
while (iterate.hasNext()) {
String key = iterate.next();
Log.v(DEBUG_TAG, key + "[" + extras.get(key) + "]");
}
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: " + result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
cursor = getContentResolver().query(Phone.CONTENT_URI,null, Phone.CONTACT_ID + "=?", new String[] { id },null);
int PhoneIdx = cursor.getColumnIndex(Phone.NUMBER);
if (cursor.moveToFirst()) {
phone = cursor.getString(PhoneIdx);
Log.v(DEBUG_TAG, "Got number: " + phone);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to get Number", e);
} finally {
if (cursor != null) {
cursor.close();
}
EditText ponenumber = (EditText) findViewById(R.id.editPhone1);
ponenumber.setText(phone);
if (phone.length() == 0) {
Toast.makeText(this, "Contact has no phone number",
Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
Whenever i run it and choose a contact i just get the "Contact has no phone number". I can't figure out why, anyone has any ideas?
Regards
You should use a "Phone picker" intent, not a "Contact picker":
static final int REQUEST_SELECT_PHONE_NUMBER = 1;
public void selectContact() {
// Start an activity for the user to pick a phone number from contacts
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(CommonDataKinds.Phone.CONTENT_TYPE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_SELECT_PHONE_NUMBER);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SELECT_PHONE_NUMBER && resultCode == RESULT_OK) {
// Get the URI and query the content provider for the phone number
Uri contactUri = data.getData();
String[] projection = new String[]{CommonDataKinds.Phone.NUMBER};
Cursor cursor = getContentResolver().query(contactUri, projection,
null, null, null);
// If the cursor returned is valid, get the phone number
if (cursor != null && cursor.moveToFirst()) {
int numberIndex = cursor.getColumnIndex(CommonDataKinds.Phone.NUMBER);
String number = cursor.getString(numberIndex);
// Do something with the phone number
...
}
}
}
Taken from the docs at:
https://developer.android.com/guide/components/intents-common.html#Contacts
To have the user select a specific piece of information from a
contact, such as a phone number, email address, or other data type,
use the ACTION_PICK action and specify the MIME type to one of the
content types listed below, such as CommonDataKinds.Phone.CONTENT_TYPE
to get the contact's phone number.
hi i am trying this code in my app i can get the contact list but when i press on contact name i didnt get any thing in my edittext which i expected to get the contact phone number
sorry about my poor english
public void doLaunchContactPicker(View view) {
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=RESULT_OK) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String phone = "";
try {
Bundle extras = data.getExtras();
Set<String> keys = extras.keySet();
Iterator<String> iterate = keys.iterator();
while (iterate.hasNext()) {
String key = iterate.next();
Log.v(DEBUG_TAG, key + "[" + extras.get(key) + "]");
}
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: "
+ result.toString());
// get the contact id from the Uri
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()) {
phone = cursor.getString(PhoneIdx);
Log.v(DEBUG_TAG, "Got number: " + phone);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to Number", e);
} finally {
if (cursor != null) {
cursor.close();
}
EditText ponenumber = (EditText) findViewById(R.id.ednum);
ponenumber.setText(phone);
if (phone.length() == 0) {
Toast.makeText(this, "No number found for contact.",
Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
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 Number=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
You're actually really close- A few things.
Your switch statement is basing off of the resultCode, not the request code. Change that- It should read "switch(requestCode)"
Phone.DATA will work, but use Phone.NUMBER instead for readability sake:)
Make sure you have the permission for android.permission.READ_CONTACTS set in your AndroidManifest.xml file, as an element inside the manifest element, but not in the application element. The line should should look like this.
<uses-permission android:name="android.permission.READ_CONTACTS" />
I made those modifications to your sample, and got working code.
you can change you code that you want get phone number,as the following
List numberList = new ArrayList();
Uri baseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,contactId);
Uri targetUri = Uri.withAppendedPath(baseUri,Contacts.Data.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(targetUri,
new String[] {Phone.NUMBER},Data.MIMETYPE+"='"+Phone.CONTENT_ITEM_TYPE+"'",null, null);
startManagingCursor(cursor);
while(cursor.moveToNext()){
numberList.add(cursor.getString(0));
}
cursor.close();
It is an old post but it could help someone.
If you just have to Pick-up a contact, you can use the first code of the post without this part:
Bundle extras = data.getExtras();
Set<String> keys = extras.keySet();
Iterator<String> iterate = keys.iterator();
while (iterate.hasNext()) {
String key = iterate.next();
Log.v(DEBUG_TAG, key + "[" + extras.get(key) + "]");
}