how can I get contact photo from a contact's address (phone number)?
public static Bitmap retrieveContactPhoto(Context context, String number) {
ContentResolver contentResolver = context.getContentResolver();
String contactId = null;
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID};
Cursor cursor =
contentResolver.query(
uri,
projection,
null,
null,
null);
if (cursor != null) {
while (cursor.moveToNext()) {
contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
}
cursor.close();
}
Bitmap photo = BitmapFactory.decodeResource(context.getResources(),
R.drawable.default_image);
try {
if(contactId != null) {
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactId)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
}
assert inputStream != null;
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return photo;
}
I think this vesion works better in all android versions :
public Bitmap getContactsDetails(String address) {
Bitmap bp = BitmapFactory.decodeResource(context.getResources(),
R.drawable.contact_default_picture);
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(address));
// querying contact data store
Cursor phones = context.getContentResolver().query(contactUri, null, null, null, null);
while (phones.moveToNext()) {
String image_uri = phones.getString(phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
if (image_uri != null) {
try {
bp = MediaStore.Images.Media
.getBitmap(context.getContentResolver(),
Uri.parse(image_uri));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return bp;
}
Call this method to get all contact information.
public void readContacts() {
StringBuffer sb = new StringBuffer();
sb.append("......Contact Details.....");
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
String phone = null;
String emailContact = null;
String emailType = null;
String image_uri = "";
Bitmap bitmap = null;
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
image_uri = cur
.getString(cur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
System.out.println("name : " + name + ", ID : " + id);
sb.append("\n Contact Name:" + name);
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
while (pCur.moveToNext()) {
phone = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
sb.append("\n Phone number:" + phone);
System.out.println("phone" + phone);
}
pCur.close();
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = ?", new String[] { id }, null);
while (emailCur.moveToNext()) {
emailContact = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
emailType = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
sb.append("\nEmail:" + emailContact + "Email type:" + emailType);
System.out.println("Email " + emailContact
+ " Email Type : " + emailType);
}
emailCur.close();
}
if (image_uri != null) {
System.out.println(Uri.parse(image_uri));
try {
bitmap = MediaStore.Images.Media
.getBitmap(this.getContentResolver(),
Uri.parse(image_uri));
sb.append("\n Image in Bitmap:" + bitmap);
System.out.println(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
sb.append("\n........................................");
}
textDetail.setText(sb);
}
}
You can use the column below to get the contacts photo uri, ContactsContract.CommonDataKinds.Phone.PHOTO_URI.
This is the function:
public static Bitmap getContactsDetails(String address) {
Bitmap bp = BitmapFactory.decodeResource(context.getResources(),
R.drawable.default_contact_photo);
String selection = ContactsContract.CommonDataKinds.Phone.NUMBER + " = '" + address + "'";
Cursor phones = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, selection,
null, null);
while (phones.moveToNext()) {
String image_uri = phones.getString(phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
if (image_uri != null) {
try {
bp = MediaStore.Images.Media
.getBitmap(context.getContentResolver(),
Uri.parse(image_uri));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return bp;
}
You can make some changes if you want to get Retrieving the larger photo
public Bitmap retrieveContactPhoto(Context context, String number) {
ContentResolver contentResolver = context.getContentResolver();
String contactId = null;
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID};
Cursor cursor =
contentResolver.query(
uri,
projection,
null,
null,
null);
if (cursor != null) {
while (cursor.moveToNext()) {
contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
}
cursor.close();
}
Bitmap photo = BitmapFactory.decodeResource(context.getResources(),
R.mipmap.popup);
try {
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.valueOf(contactId));
Uri displayPhotoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
AssetFileDescriptor fd =
getContentResolver().openAssetFileDescriptor(displayPhotoUri, "r");
InputStream inputStream=fd.createInputStream();
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
}
assert inputStream != null;
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return photo;
}
for Retrieving the thumbnail-sized photo
public InputStream openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri,
new String[] {Contacts.Photo.PHOTO}, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return new ByteArrayInputStream(data);
}
}
} finally {
cursor.close();
}
return null;
}
for more detail:
Click Here
Related
In my code the contact fetching takes too much time to fetch the contacts and show in the application.
Please guide me where i am wrong and what should i correct in order to make execution time fast.
Here is my code.
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null );
String phone = null;
List<String> phonenumber = new ArrayList<String>();
String emailContact = null;
String emailType = null;
String image_uri = "";
Bitmap bitmap = null;
if (cur.getCount() > 0) {
while (cur.moveToNext())
{
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
image_uri = cur
.getString(cur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
System.out.println("name : " + name + ", ID : " + id);
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[]{id}, null);
Log.e("pCur","dfgfdg "+pCur.getCount());
while (pCur.moveToNext())
{
phone = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// contactid=pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
/* phonenumber.add(pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));`*/
Log.e("phone" ,phone);
}
pCur.close();
Cursor emailCur = cr.query
(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = ?", new String[]{id}, null);
while (emailCur.moveToNext())
{
emailContact = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
if(TextUtils.isEmpty(emailContact)||emailContact.equalsIgnoreCase(null)||emailContact.equalsIgnoreCase(""))
{
emailContact="";
Log.e("isEmpty","isEmpty " + emailContact);
}
else
{
Log.e("gfdszfg","Email " + emailContact);
}
/* emailType = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));*/
Log.e("gfdszfg","Email " + emailContact);
}
emailCur.close();
}
if (image_uri != null)
{
System.out.println(Uri.parse(image_uri));
try
{
bitmap = MediaStore.Images.Media
.getBitmap(this.getContentResolver(),
Uri.parse(image_uri));
System.out.println(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mList.add(new Contacts(name, phone, image_uri,emailContact));
emailContact="";
}
cur.close();
mMyContactsAdapter = new MyContactsAdapter(MainActivity.this, mList);
mcontact.setAdapter(mMyContactsAdapter);
}
and more over in my code my contact fetching while loop is looping 3 times i dont know why.
I have faced this situation as you are in right now. Try below code
public static ArrayList ReadContactsSpecialWay(Context context) {
StringBuffer contactBuffer = new StringBuffer();
StringBuffer emailBuffer = new StringBuffer();
ArrayList<String> contactList = new ArrayList<>();
ArrayList<String> emailList = new ArrayList<>();
ArrayList<ContactModel> contactModelsList = new ArrayList<>();
HashMap<Integer, Boolean> hashMap = new HashMap<Integer, Boolean>();
String[] emailsAndContacts = new String[2];
// Phone numbers
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection = new String[]{
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
Cursor phoneNumbers = context.getContentResolver().query(uri, projection, null, null, null);
int indexContactID = phoneNumbers.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
int indexName = phoneNumbers.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int indexNumber = phoneNumbers.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
while (phoneNumbers.moveToNext()) {
Integer contactId = phoneNumbers.getInt(indexContactID);
String contactName = phoneNumbers.getString(indexName);
String contactNumber = phoneNumbers.getString(indexNumber).replace(" ", "");
ContactModel contactModel = new ContactModel();
contactModel.setContactPhone(contactNumber);
contactNumber = contactModel.getContactPhone();
if (hashMap.containsKey(contactId))
contactModel.setContactName(contactName + " (" + contactNumber + ")");
else {
hashMap.put(contactId, true);
contactModel.setContactName(contactName);
}
contactModelsList.add(contactModel);
contactList.add(contactNumber);
LogHelper.informationLog(contactNumber + " " + contactName);
contactBuffer.append(contactNumber + ",");
}
phoneNumbers.close();
// Emails
uri = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
projection = new String[]{
ContactsContract.CommonDataKinds.Email.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Email.DATA
};
Cursor emails = context.getContentResolver().query(uri, projection, null, null, null);
indexContactID = emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID);
indexName = emails.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int indexData = emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
while (emails.moveToNext()) {
Integer contactId = emails.getInt(indexContactID);
String contactName = emails.getString(indexName);
String contactEmail = emails.getString(indexData).toLowerCase();
ContactModel contactModel = new ContactModel();
contactModel.setEmailAddress(contactEmail);
if (hashMap.containsKey(contactId)) {
contactModel.setEmailName(contactName + " (" + contactEmail + ")");
} else {
contactModel.setEmailName(contactName);
hashMap.put(contactId, true);
}
contactModelsList.add(contactModel);
if (contactEmail != null && !emailList.contains(contactEmail)) {
emailList.add(contactEmail);
LogHelper.informationLog(contactEmail + " " + contactName);
emailBuffer.append(contactEmail + ",");
}
}
emails.close();
if (contactBuffer.toString().length() > 0) {
emailsAndContacts[0] = contactBuffer.toString().substring(0, (contactBuffer.toString().length() - 1));
} else
emailsAndContacts[0] = "";
if (emailBuffer.toString().length() > 0) {
emailsAndContacts[1] = emailBuffer.toString();
} else {
emailsAndContacts[1] = "";
}
if(contactModelsList.size() == 0)
return null;
else {
ArrayList specialList = new ArrayList();
specialList.add(contactModelsList);
specialList.add(emailsAndContacts);
return specialList;
}
}
It will definitely help you out.
Try this, using AsyncTask. Use it while launching apps default activity on background and fetch the array while using on another activity
class LoadContact extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
// Get Contact list from Phone
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
ContentResolver contentResolver = getContentResolver();
/**
* #discussion Query contact and return name and contact Id.
*/
Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
Bitmap bit_thumb = null;
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
String image_thumb = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI));
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
try {
if (image_thumb != null) {
bit_thumb = MediaStore.Images.Media.getBitmap(contentResolver, Uri.parse(image_thumb));
}
} catch (IOException e) {
e.printStackTrace();
}
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
final SelectUser selectUser = new SelectUser();
selectUser.setName(name);
selectUser.setContactId(contact_id + "" + phoneNumber);
selectUser.setThumb(bit_thumb);
selectUser.setPhone(phoneNumber);
if (selectUser.getPhone() != null && selectUser.getPhone().length() > 0 && !num.equalsIgnoreCase(phoneNumber)) {
num = phoneNumber;
selectUsers.add(selectUser);
}
}
phoneCursor.close();
Cursor cur1 = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{contact_id}, null);
while (cur1.moveToNext()) {
String email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
final SelectUser selectUser = new SelectUser();
selectUser.setName(name);
selectUser.setContactId(contact_id + "" + email);
selectUser.setThumb(bit_thumb);
selectUser.setEmail(email);
if (selectUser.getEmail() != null && selectUser.getEmail().length() > 0 && !userEmail.equalsIgnoreCase(email)) {
userEmail=email;
selectUsers.add(selectUser);
}
}
cur1.close();
}
}
cursor.close();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
isContactLoaded = true;
}
}
This code fetching contacts, name and photo from contact list but it is taking too much time in fetching all these.
So my problem is if user has more then 500 contacts then its taking to much time so how to decreasing its fetching time.
I have seen many posts on Stack Overflow but unable to find solution.
public void fetchContacts() {
list = new ArrayList<PersonDetails>();
String phoneNumber = null;
//Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
Uri CONTENT_URI= ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
// StringBuffer output = new StringBuffer();
String[] PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER, };
String SELECTION = ContactsContract.Contacts.HAS_PHONE_NUMBER
+ "='1'";
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, PROJECTION,
SELECTION, null, null);
// Loop for every contact in the phone
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
//Log.e("i", i + "");
PersonDetails personDetails = null;
String contact_id = cursor.getString(cursor
.getColumnIndex(_ID));
String name = cursor.getString(cursor
.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor
.getString(cursor
.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
// Query and loop for every phone number of the
// contact
String Phone_Projection[] = new String[] { Phone.NUMBER };
Cursor phoneCursor = contentResolver.query(
PhoneCONTENT_URI, Phone_Projection,
Phone_CONTACT_ID + " = ?",
new String[] { contact_id }, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor
.getColumnIndex(NUMBER));
// output.append("\n Phone number:" +
// phoneNumber);
}
phoneCursor.close();
if (phoneNumber != null
&& phoneNumber.length() >= 10) {
Uri ur = null;
try {
Uri person = ContentUris
.withAppendedId(
ContactsContract.Contacts.CONTENT_URI,
Long.parseLong(contact_id));
ur = Uri.withAppendedPath(
person,
ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
personDetails = new PersonDetails();
if (name != null) {
personDetails.setName(name);
}
if (phoneNumber != null) {
//Log.e("Phone", phoneNumber);
personDetails.setSocialId(phoneNumber);
}
if (ur != null) {
//Log.e("URI", ur.toString());
personDetails.setPhotoUrl(ur.toString());
}
personDetails.setSocialFlag(5);
}
}
if (personDetails != null) {
list.add(personDetails);
}
}
}
try {
if (cursor != null) {
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I am trying to get id, firstName, lastName, fullName and photo from contacts. I used the following code for that,
but it takes too long to fetch data, at least 10 seconds. I used this code on thread so my activity won't freeze
but it takes too long to get all the data.
String[] projection = new String[] {ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME_ALTERNATIVE,
ContactsContract.Contacts.DISPLAY_NAME,
};
Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, projection, null,
null, null);
cursor.moveToFirst();
if (cursor.getCount() > 0) {
do {
try {
contactId = cursor
.getString(cursor
.getColumnIndex(ContactsContract.Contacts._ID));
Uri contactUri = ContentUris.withAppendedId(
Contacts.CONTENT_URI,
Long.parseLong(contactId));
Uri dataUri = Uri.withAppendedPath(contactUri,
Contacts.Data.CONTENT_DIRECTORY);
Cursor phones = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = " + contactId,
null, null);
if (phones.getCount() > 0) {
ContactClass info = new ContactClass();
info.setid(contactId);
try {
Cursor nameCursor =
getContentResolver()
.query(dataUri,
null,
Data.MIMETYPE + "=?",
new String[] { StructuredName.CONTENT_ITEM_TYPE },
null);
nameCursor.moveToFirst();
do {
String firstName = nameCursor
.getString(nameCursor
.getColumnIndex(Data.DATA2));
String lastName = "";
String displayname = cursor
.getString(cursor
.getColumnIndex(Contacts.DISPLAY_NAME_ALTERNATIVE));
if (!firstName.equals(displayname)) {
lastName = nameCursor
.getString(nameCursor
.getColumnIndex(Data.DATA3));
}
// check lastName Value
if (firstName.equals(null)
&& lastName.equals(null)) {
info.setfirstname("unknown name");
} else if (firstName.equals(null)) {
info.setlastname(lastName);
} else if (lastName.equals(null)) {
info.setfirstname(firstName);
} else {
info.setfirstname(firstName);
info.setlastname(lastName);
}
} while (nameCursor.moveToNext());
nameCursor.close();
info.setphoto(retrieveContactPhoto(contactId));
contactinfo.add(info);
} catch (Exception e) {
}
}
phones.close();
}
catch (Exception t) {
}
} while (cursor.moveToNext());
cursor.close();
retrieveContactPhoto():
private String retrieveContactPhoto(String contactID) {
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;
}
What do you recommend I should do to improve the perfomance of the above code?
i try this code to fetch my contact
try {
String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
+ Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ Contacts.DISPLAY_NAME + " != '' ))";
Cursor c = cntx.getContentResolver().query(Contacts.CONTENT_URI, CONTACTS_SUMMARY_PROJECTION, select,
null, Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
for(int i=0;i<c.getCount();i++)
{
// contactWrap.clear();
try {
contactId = 0;
String hasPhone = "";
display_name = "";
phoneNumber = "";
c.moveToPosition(i);
contactId = c.getLong(0);
display_name = c.getString(1);
hasPhone = c.getString(7);
if (hasPhone.equalsIgnoreCase("1"))
hasPhone = "true";
else
hasPhone = "false" ;
if (Boolean.parseBoolean(hasPhone))
{
Cursor phones = cntx.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
while (phones.moveToNext())
{
int indexPhoneType = phones.getColumnIndexOrThrow(Phone.TYPE);
String phoneType = phones.getString(indexPhoneType);
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
contactWrap.add(new ContactsWrapper(contactId, display_name, phoneNumber,lookupKey,false,color_string));
}
// map.put(contactId, new ArrayList<ContactsWrapper>(contactWrap));
phones.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
ohk u can take contactID from this cursor or your code now this is my method which will give u contact photo just pass contact ID in it
public InputStream openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri,
new String[] {Contacts.Photo.PHOTO}, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return new ByteArrayInputStream(data);
}
}
} finally {
cursor.close();
}
return null;
}
Hope this will help u Best of luck dude
I'm trying to get a contact image using its lookup URI.
I succeed getting the DISPLAY_NAME using this code:
Cursor c = context.getContentResolver().query(contactLookupUri,
new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null,
null, null);
But I didn't find a way to get the photo. The Photo.PHOTO option is not valid for the API I'm using, and trying to get it using an inputStream didn't work as well (perhaps I did something wrong there):
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(context.getContentResolver(),
contactUri);
Thanks,
Yoel
Eventually I solved it by getting the contact ID and using an inputStream:
public static Uri getContactLookupUri(String contactLookupKey) {
return Uri.withAppendedPath(
ContactsContract.Contacts.CONTENT_LOOKUP_URI, contactLookupKey);
}
public static Bitmap getContactImage(Context context, String contactLookupKey) {
long contactId;
try {
Uri contactLookupUri = getContactLookupUri(contactLookupKey);
Cursor c = context.getContentResolver().query(contactLookupUri,
new String[] { ContactsContract.Contacts._ID }, null, null,
null);
try {
if (c == null || c.moveToFirst() == false) {
return null;
}
contactId = c.getLong(0);
} finally {
c.close();
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Uri contactUri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, contactId);
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(context.getContentResolver(),
contactUri);
if (input != null) {
return BitmapFactory.decodeStream(input);
} else {
return null;
}
}
The below function return the image uri of your contact_id
/**
* #return the photo URI
*/
public Uri getPhotoUri() {
try {
Cursor cur = this.ctx.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID + "=" + this.getId() + " AND "
+ ContactsContract.Data.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'", null,
null);
if (cur != null) {
if (!cur.moveToFirst()) {
return null; // no photo
}
} else {
return null; // error in cursor process
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long
.parseLong(getId()));
return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}
Also refer this LINK
if there any method to get contact name by send contact number in android.if any one have idea .
private String getContactName(String string) {
String name=null;
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null,null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
}
return name;
}
I am sending contact number to these method.How to get contact name.
use following method to get contact, from contact provider:
Uri contactUri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, Uri.encode(string));
Cursor cursor = mContext.getContentResolver().query(contactUri, null, null, null, null);
This cursor will have resultset having number same as string.
I got it by do like these.
public static String getContactName(final String phoneNumber,Context context) {
Uri uri;
String[] projection;
Uri mBaseUri = Contacts.Phones.CONTENT_FILTER_URL;
projection = new String[] { android.provider.Contacts.People.NAME };
try {
Class<?> c = Class
.forName("android.provider.ContactsContract$PhoneLookup");
mBaseUri = (Uri) c.getField("CONTENT_FILTER_URI").get(mBaseUri);
projection = new String[] { "display_name" };
} catch (Exception e) {
}
uri = Uri.withAppendedPath(mBaseUri, Uri.encode(phoneNumber));
Cursor cursor = context.getContentResolver().query(uri, projection, null,
null, null);
String contactName = "";
if (cursor.moveToFirst()) {
contactName = cursor.getString(0);
}
cursor.close();
cursor = null;
return contactName;
}
Try
Uri uri;
String[] projection;
Uri baseUri = Contacts.Phones.CONTENT_FILTER_URL;
projection = new String[] { android.provider.Contacts.People.NAME };
try {
Class<?> c = Class.forName("android.provider.ContactsContract$PhoneLookup");
baseUri = (Uri) c.getField("CONTENT_FILTER_URI").get(baseUri);
projection = new String[] { "display_name" };
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
uri = Uri.withAppendedPath(baseUri, Uri.encode(Uri
.encode(phoneNumber)));
Cursor cursor =mContext.getContentResolver().query(uri,
projection, null, null, null) ;
String fromDisplayName = null;
if (cursor != null) {
if (cursor.moveToFirst()){
fromDisplayName = cursor.getString(0);
}
else{
fromDisplayName="";
}
cursor.close();
} else {
fromDisplayName="";
}
return fromDisplayName;
The Uri android.provider.Contacts.People.NAME is deprecated. But android.provider.ContactsContract$PhoneLookup is available from API level 5 only. Hence it is better to use reflections to support all phones.