How to programmatically link a contact number? - android

I want to develop contact application with basic CRUD operations with Contacts, and Mostly Link Contact Numbers using Android.

Try this it works for me :
public class MyActivity extends Activity {
private static final String TAG = MyActivity.class.getSimpleName();
private static final int REQUEST_CODE_PICK_CONTACTS = 1;
private Uri uriContact;
private String contactID; // contacts unique ID
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
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();
}
}
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();
}
}
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);
}
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);
}
}
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select a Contact"
android:onClick="onClickSelectContact" />
<ImageView android:id="#+id/img_contact"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:adjustViewBounds="true"
android:contentDescription="Contacts Image"
/>
and add this to menifest file :
<uses-permission android:name="android.permission.READ_CONTACTS" />

Related

fetching multiple contacts from phone book and display

The problem which i'm facing is I am not able to display the fetched value, as I have used a list view to display the values are not reaching it. This is my code snippet which fetches multiple contacts from phone book. Hope any1 help me solve it.
private void chooseContact() {
Intent phonebookIntent = new Intent("intent.action.INTERACTION_TOPMENU");
phonebookIntent.putExtra("additional", "phone-multi");
phonebookIntent.putExtra("maxRecipientCount", MAX_PICK_CONTACT);
phonebookIntent.putExtra("FromMMS", true);
startActivityForResult(phonebookIntent, REQUEST_CODE_PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == RESULT_PICK_CONTACT) {
Uri contractData = data.getData();
ContactRetriever cr = new ContactRetriever(getApplicationContext(), contractData);
Person p = cr.getPerson();
if (p == null)
Toast.makeText(this, "Phone number not found!", Toast.LENGTH_SHORT).show();
else {
PersonManager.savePerson(p, getApplicationContext());
listContacts.setAdapter(new PersonAdapter(this, PersonManager.getSavedPersons(this)));
}
}
}
}}
And the Uri value is called and used in next below class
public class ContactRetriever {
private final String TAG = "ContactRetriever";
private ContentResolver cr;
private Context context;
private Uri contractData;
private String id;
public ContactRetriever(Context context,Uri contractData ) {
this.context = context;
this.cr = context.getContentResolver();
this.contractData = contractData;
}
public Person getPerson() {
String name = getName();
String num = getNumber();
if (name != null && num != null)
return new Person(getNumber(), getName());
else return null;
}
private String getNumber() {
String ret = null;
Cursor cId = cr.query(contractData, new String[]{ContactsContract.Contacts._ID}, null, null, null);
if (cId.moveToFirst()){
id = cId.getString(cId.getColumnIndex(ContactsContract.Contacts._ID));
Log.i(TAG + " IDs: ", id);
}
cId.close();
Cursor cNum = cr.query(contractData, null, null, null, null);
if (cNum.moveToNext()){
ret = cNum.getString(cNum.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i(ret, TAG + " NUMBERS: ");
}
return ret;
}
private String getName() {
String ret = null;
Cursor c = cr.query(contractData, null, null, null, null);
if (c.moveToFirst())
ret = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
c.close();
Log.i(TAG + "NAMES: ", ret);
return ret;
}
}
Here is my working code for mine
//enter code here
private void getAllContacts() {
List<InviteContactInfo> inviteContactList = new ArrayList();
InviteContactInfo inviteContactInfo;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
inviteContactInfo = new InviteContactInfo();
inviteContactInfo.setContactName(name);
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id},
null);
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
inviteContactInfo.setContactNumber(phoneNumber);
}
phoneCursor.close();
Cursor emailCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCursor.moveToNext()) {
String emailId = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
Bitmap photo =null;
try {
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
inviteContactInfo.setContactImage(photo);
}
else
{
photo =BitmapFactory.decodeResource(getResources(), R.drawable.profilepic);;
inviteContactInfo.setContactImage(photo);
}
assert inputStream != null;
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
inviteContactList.add(inviteContactInfo);
}
}
InviteContactAdapter contactAdapter = new InviteContactAdapter(getApplicationContext(), inviteContactList);
recList.setLayoutManager(new LinearLayoutManager(this));
recList.setAdapter(contactAdapter);
}
}

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

retrieving photo and name from contacts in android [duplicate]

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

Email is not displayed in the List?

The code I am using will display the Name and Number in the listview, but I need to display the Email also, for that I added some code snippet but Email didn't display in the listview. I am using Android 2.1 platform.
CODE
public class Trial2 extends Activity {
/** Called when the activity is first created. */
private static final int CONTACT_PICKER_RESULT = 1001;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button Btn = (Button)findViewById(R.id.button1);
Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(i, CONTACT_PICKER_RESULT);
}
});
}
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if(resultCode == RESULT_OK) {
switch (reqCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
Cursor Emails = null;
String number = "";
String mailid;
try {
Uri result = data.getData();
//get the id from the uri
String id = result.getLastPathSegment();
//query
cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone._ID + " = ? " , new String[] {id}, null);
int numberIdx = cursor.getColumnIndex(Phone.DATA);
if(cursor.moveToFirst()) {
number = cursor.getString(numberIdx);
} else {
}
Emails = getContentResolver().query(Email.CONTENT_URI,null,Email.CONTACT_ID + " = " + id, null, null);
int emailid = Emails.getColumnIndex(Email.DATA);
if(Emails.moveToFirst()){
mailid =Emails.getString(emailid);
}else {
}
} catch (Exception e) {
//failed
} finally {
if (cursor!=null) {
cursor.close();
}
}
}
}
}
}
Xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Trial2" />
</LinearLayout>
Solution ? Please.
Try this code snippet to display your Email in listview.This will be helpful
Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = ?", new String[]{id}, null);
while (emailCur.moveToNext()) {
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
} emailCur.close();
use this code for getting email
Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = ?", new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
}
emailCur.close();
after getting values of gmail id you have to pass those values into listview , in your code there is no listview in the activity check that once......

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

Categories

Resources