retrieving photo and name from contacts in android [duplicate] - android

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

Related

Retrieving Phone Number from Android Contacts Doesn't Work On Samsung

When I put the code in starting from the line "// Using the contact ID now we will get contact phone number" to the line "cursorPhone.close", it doesn't display any contact info on my s3 or note 3, but does display it on my asus tablet. If i take out the code between the lines mentioned above, the code works on s3 and note 3. What am i doing wrong? There are no errors in the log.
private void getContacts() {
try {
String[] projection = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
ContactsContract.Contacts._ID };
mCursor = managedQuery(ContactsContract.Contacts.CONTENT_URI,
projection, ContactsContract.Contacts.HAS_PHONE_NUMBER + "=?", new String[] { "1" },
ContactsContract.Contacts.DISPLAY_NAME);
String phoneNumber = '';
while (mCursor.moveToNext()) {
contact contact = new contact();
String contactId = mCursor.getString(mCursor.getColumnIndex(ContactsContract.Contacts._ID));
contact.setContactName(mCursor.getString(mCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
// Using the contact ID now we will get contact phone number
Cursor cursorPhone = 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()) {
phoneNumber = (cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
cursorPhone.close();//till here
contact_list.add(contact);
}
isChecked = new boolean[mCursor.getCount()];
for (int i = 0; i < isChecked.length; i++) {
isChecked[i] = false;
}
this.mContactAdapter = new contactAdapter(this, R.layout.contactlistview, contact_list);
lv.setAdapter(this.mContactAdapter);
mCursor.close();
runOnUiThread(returnRes);
} catch (Exception e) {
Log.d("getContacts", e.getMessage());
}
}
why dont you try to open inbuild Contact activity using -
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT); Hope this helps you.
You need to handle code In Activity Result Method of Activty like this:
if (reqCode == PICK_CONTACT && resultCode == Activity.RESULT_OK) {
// final String phoneNumber = data.getStringExtra("android.intent.extra.PHONE_NUMBER");
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
number=number.replaceAll("\\s", "");
number=number.replaceAll("-", "");
edtPhoneNumber.setText(number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
finishActivity(PICK_CONTACT);
}
if (reqCode == PICK_CALLLOG && resultCode == Activity.RESULT_OK) {
edtPhoneNumber.setText(data.getStringExtra("CallerNumber"));
}
if (reqCode == PICK_SMSLOG && resultCode == Activity.RESULT_OK) {
edtPhoneNumber.setText(data.getStringExtra("CallerNumber"));
}
}

Android Read Contact Information

I am calling intent to pick a contact using this code.
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
((Activity) mContext).startActivityForResult(intent, PICK_CONTACT);
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (reqCode == PICK_CONTACT) {
if (resultCode == Activity.RESULT_OK) {
Uri uri= data.getData();
}
Here I want to fetch three information of contact such as Name, Phone number, and contact Image.
I am able to fetch name and number but not able to fetch Image. any help would be appreciated.
use following function:
private String retrieveContactPhoto(String contactID) {
// Bitmap photo = null;
/*
* if (inputStream != null) { photo =
* BitmapFactory.decodeStream(inputStream); ImageView imageView =
* (ImageView) findViewById(R.id.img_contact);
* imageView.setImageBitmap(photo); }
*/
Uri photoUri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI,
Long.parseLong(contactID));
final Cursor image = getContentResolver().query(photoUri,
PHOTO_ID_PROJECTION, null, null,
ContactsContract.Contacts._ID + " ASC");
try {
Integer thumbnailId = null;
if (image.moveToFirst()) {
thumbnailId = image.getInt(image
.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
Uri uri = ContentUris.withAppendedId(
ContactsContract.Data.CONTENT_URI, thumbnailId);
image.close();
if (uri.toString().equals("content://com.android.contacts/data/0"))
return null;
return uri.toString();
}
} finally {
image.close();
}
return null;
and for showing image use following code
if (entries.get(position).getphoto() != null
&& entries.get(position).getphoto() != "content:////com.android.contacts//data//0") {
try {
holder.photo.setImageURI(Uri.parse(entries.get(position)
.getphoto()));
} catch (Exception e) {
holder.photo.setImageResource(R.drawable.abc); //use default image
}
} else
holder.photo.setImageResource(R.drawable.abc); //use default image
Try following
InputStream photo_stream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),uri);
BufferedInputStream buf =new BufferedInputStream(photo_stream);
Bitmap my_btmp = BitmapFactory.decodeStream(buf);
Use this:
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(this.getContentResolver(), uri);
BufferedInputStream buffer =new BufferedInputStream(input);
Bitmap bitmap = BitmapFactory.decodeStream(buffer);
Check the below code which will help you to get the Contact Name,Number and contact Image as well. Call the below code on click of a button.
public void onClickSelectContact(View btnSelectContact) {
// using native contacts selection
// Intent.ACTION_PICK = Pick an item from the data, returning what was selected.
startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), REQUEST_CODE_PICK_CONTACTS);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_PICK_CONTACTS && resultCode == RESULT_OK) {
Log.d(TAG, "Response: " + data.toString());
uriContact = data.getData();
retrieveContactName();
retrieveContactNumber();
retrieveContactPhoto();
}
}
//To get the Contact Image
private void retrieveContactPhoto() {
Bitmap photo = null;
try {
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactID)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
ImageView imageView = (ImageView) findViewById(R.id.img_contact);
imageView.setImageBitmap(photo);
}
assert inputStream != null;
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//To get Contact Number.
private void retrieveContactNumber() {
String contactNumber = null;
// getting contacts ID
Cursor cursorID = 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.d(TAG, "Contact ID: " + contactID);
// Using the contact ID now we will get contact phone number
Cursor cursorPhone = 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));
}
cursorPhone.close();
Log.d(TAG, "Contact Phone Number: " + contactNumber);
}
//To get Contact Name.
private void retrieveContactName() {
String contactName = null;
// querying contact data store
Cursor cursor = 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));
}
cursor.close();
Log.d(TAG, "Contact Name: " + contactName);
}
}
Also to get all the phone numbers + email address try as below:
ContentResolver contactResolver = context.getContentResolver();
Cursor cursor = contactResolver.query(Uri.parse(aContact.getLookupUri()), null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String photoUri = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = contactResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { contactId }, null);
while (pCur.moveToNext())
{
String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String type = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
String s = (String) ContactsContract.CommonDataKinds.Phone.getTypeLabel(context.getResources(), Integer.parseInt(type), "");
Log.d("TAG", s + " phone: " + phone);
}
pCur.close();
}
Cursor emailCursor = contactResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] { contactId }, null);
while (emailCursor.moveToNext())
{
String phone = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
int type = emailCursor.getInt(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
String s = (String) ContactsContract.CommonDataKinds.Email.getTypeLabel(context.getResources(), type, "");
Log.d("TAG", s + " email: " + phone);
}
emailCursor.close();
cursor.close();
}

How to Get Contact name, number and emai ID from a list of contacts?

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();
}
}
}

Access contacts and get email address

I have a code snippet for accessing to Contacts. When user click the button then the contacts list will be open and user can choose a person from contacts and the person's email address should be write on a edittext. I can receive the email from the persons which user select. But I can't set it to the edittext.
static String email = "";
imgbtnaddfromcontacts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (v == imgbtnaddfromcontacts) {
try
{
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, 1);
} catch (Exception e) {
e.printStackTrace();
Log.e("Error in intent : ", e.toString());
}
}
}
});
kimeTxt.setText(email);
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
try {
if (resultCode == Activity.RESULT_OK) {
// Get data
Uri contactData = data.getData();
// Cursor
Cursor cur = managedQuery(contactData, null, null, null, null);
ContentResolver contect_resolver = getContentResolver();
// List
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);
Cursor emailCur = contect_resolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = ?", new String[] { id }, null);
if (phoneCur.moveToFirst()) {
name = phoneCur
.getString(phoneCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
no = phoneCur
.getString(phoneCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
email = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
if (email != null)
{
seciliEmail = email;
} else {
Toast.makeText(EpostaIletActivity.this,
"Kişinin eposta hesabı bulunmamaktadır.",
Toast.LENGTH_SHORT);
Log.w("Error: ", "Kişinin eposta hesabı yok.");
}
}
Log.e("Phone no & name & email :***: ", name + " : " + no + ":" + email);
// txt.append(name + " : " + no + "\n");
id = null;
name = null;
no = null;
seciliEmail = "xxx";
phoneCur = null;
emailCur.close();
}
contect_resolver = null;
cur = null;
// populateContacts();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
Log.e("IllegalArgumentException :: ", e.toString());
} catch (Exception e) {
e.printStackTrace();
Log.e("Error :: ", e.toString());
}
}
Am using below code for getting email address from selected contact -
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");
}
}
doLaunchContactPicker is an onclick of Button Use the code wherever you wants.
make sure your app has got permission, otherwise you'll get weird Exceptions
in AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_CONTACTS" />
You can achieve it like this
public class Abc extends Activity{
EditText kimeTxt;
Intent i;
Bundle b ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_course);
kimeTxt= (EditText)findViewById(R.id.emailid);
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
try {
if (resultCode == Activity.RESULT_OK) {
// Get data
Uri contactData = data.getData();
// Cursor
Cursor cur = managedQuery(contactData, null, null, null, null);
ContentResolver contect_resolver = getContentResolver();
// List
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);
Cursor emailCur = contect_resolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = ?", new String[] { id }, null);
if (phoneCur.moveToFirst()) {
name = phoneCur
.getString(phoneCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
no = phoneCur
.getString(phoneCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
email = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
if (email != null)
{
seciliEmail = email;
} else {
Toast.makeText(EpostaIletActivity.this,
"Kişinin eposta hesabı bulunmamaktadır.",
Toast.LENGTH_SHORT);
Log.w("Error: ", "Kişinin eposta hesabı yok.");
}
}
Log.e("Phone no & name & email :***: ", name + " : " + no + ":" + email);
// txt.append(name + " : " + no + "\n");
id = null;
name = null;
no = null;
seciliEmail = "xxx";
phoneCur = null;
emailCur.close();
}
// can set email id here
kimeTxt.setText(email);
contect_resolver = null;
cur = null;
// populateContacts();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
Log.e("IllegalArgumentException :: ", e.toString());
} catch (Exception e) {
e.printStackTrace();
Log.e("Error :: ", e.toString());
}
}

No phonenr from ContactsContract

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.

Categories

Resources