Fetch Local phonebook contacts From SIM card only android - android

I want to know if its possible to fetch contacts which exist in SIM card or phonebook only. Right now I am using the following code to fetch contacts and it fetches all the contacts even my gmail and Facebook Contacts.
Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0)
{
while (cursor.moveToNext())
{
PhoneBookUserEntity user = new PhoneBookUserEntity();
// Pick out the ID, and the Display name of the
// contact from the current row of the cursor
user.setId(cursor.getString(cursor.getColumnIndex(BaseColumns._ID)));
user.setPhoneBookName(cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME)));
if(user.getphonebookname().length() > 4)
username = user.getphonebookname();//.substring(0,4);
else
username = user.getphonebookname();//.substring(0,1);
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
// if (Boolean.parseBoolean(hasPhone)) {
Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ user.getId(), null, null);
while (phones.moveToNext()) {
user.sePhoneNumber(phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
phones.close();
//}
// user.sePhoneNumber(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + user.getId(), null, null);
while (emails.moveToNext()) {
// This would allow you get several email addresses
user.setEmailAddress(emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)));
}
emails.close();
user.setImageURI(getPhotoUri(user.getId()));
SearchContactsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
_progressDialog.setMessage("Copying over your local phone book. Retrieving contact information for \n"+ username.toUpperCase());
}
});
arraylist.add(user);
}
}
cursor.close();

For Sim contact only you can use below code
private void allSIMContact()
{
try
{
String ClsSimPhonename = null;
String ClsSimphoneNo = null;
Uri simUri = Uri.parse("content://icc/adn");
Cursor cursorSim = this.getContentResolver().query(simUri,null,null,null,null);
Log.i("PhoneContact", "total: "+cursorSim.getCount());
while (cursorSim.moveToNext())
{
ClsSimPhonename =cursorSim.getString(cursorSim.getColumnIndex("name"));
ClsSimphoneNo = cursorSim.getString(cursorSim.getColumnIndex("number"));
ClsSimphoneNo.replaceAll("\\D","");
ClsSimphoneNo.replaceAll("&", "");
ClsSimPhonename=ClsSimPhonename.replace("|","");
Log.i("PhoneContact", "name: "+ClsSimPhonename+" phone: "+ClsSimphoneNo);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}

Cursor cursor = getContacts();
getBundleValues2();
String displayName = "";
while (cursor.moveToNext()) {
//taking id name and phone number from contacts using content provider
String displayid = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts._ID));
displayName = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String displayphnno = "";
ContentResolver cr = getContentResolver();
if (Integer.parseInt(cursor.getString(cursor
.getColumnIndex(ContactsContract.Data.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { displayid }, null);
while (pCur.moveToNext()) {
displayphnno = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
+ "\n";
ContactProviderViewGroup v6;
//using view group appending it to an activity
if (colorFlag) {
v6 = new ContactProviderViewGroup(this, displayName,
displayphnno, passedid, colorFlag);
colorFlag = false;
} else {
v6 = new ContactProviderViewGroup(this, displayName,
displayphnno, passedid, colorFlag);
colorFlag=true;
}
LL1.addView(v6);
}
pCur.close();
}
}
}
private void getBundleValues2() {
Intent i = getIntent();
Bundle myBundle = i.getExtras();
if (myBundle != null) {
passedid = myBundle.getInt("gid");
}
}
private Cursor getContacts() {
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER };
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
}

Related

how to separate multiple phones from a single contact

how can I separate the phones from a contact if it has multiple numbers, as seen in the image
MG8ou.png
here my code
#Override
protected Void doInBackground(Void... params) {
ContentResolver contentResolver = getActivity().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));
ContactObjets contactObjets = new ContactObjets();
contactObjets.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));
contactObjets.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));
contactObjets.setContactEmail(emailId);
}
emailCursor.close();
contactObjetsList.add(contactObjets);
}
}
}
return null;
}
I have it inside an AsyncTask that is this asu you see inside a dialog but it only calls the first number, but if it has more than one number the contact does not do it.
how can i solve my problem
#Override
protected Void doInBackground(Void... params) {
ContentResolver contentResolver = getActivity().getContentResolver();
Cursor cursor = contentResolver.query(
Contacts.CONTENT_URI,
null,
null,
null,
Phone.DISPLAY_NAME + " ASC");
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME));
Cursor phoneCursor = contentResolver.query(
Phone.CONTENT_URI,
null,
Phone.CONTACT_ID + " = ?",
new String[]{id},
null);
if (phoneCursor.moveToNext()) {
for (int i = 0; phoneCursor.getCount() > i; i++ ){
phoneCursor.moveToPosition(i);
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(Phone.NUMBER));
int typePhone = phoneCursor.getInt(phoneCursor.getColumnIndex(Phone.TYPE));
String type = "";
switch (typePhone){
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
type = "Casa";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
type = "Celular";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
type = "Trabajo";
break;
default:
type = "Otro";
break;
}
ContactObjets contactObjets = new ContactObjets();
contactObjets.setContactName(name);
contactObjets.setContactNumber(phoneNumber);
contactObjets.setContactType(type);
contactObjetsList.add(contactObjets);
}
}
phoneCursor.close();
}
return null;
}

Getting null value while retrieving the CONTACT NAME from CONTACT EMAIL

I want to retrieve the contact name from the contact email, so what I have done is as follows from https://stackoverflow.com/a/18064869/5738881.
public static String readContacts(Context context, String email) {
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(email));
Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
if (cursor == null) {
return null;
}
String contactName = null;
if (cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
if (!cursor.isClosed()) {
cursor.close();
}
Log.e("....contact name....", email + "\n" + contactName);
return contactName;
}
Then in onCreate(), I have coded as,
sName = readContacts(getApplicationContext(), sEmail);
etName.setText(sName);
But I am getting the null value. Therefore what could be the soution to fetch contact name, depending upon just the contact email address?
EDIT-1:
I have already mentioned the permission in manifest as,
<uses-permission android:name="android.permission.READ_CONTACTS"/>
EDIT-2:
As per ROHIT SHARMA's answer, I changed my code as below.
public static String readContacts(Context context, String email) {
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(email));
Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
if (cursor == null) {
return null;
}
String contactName = null;
if (cursor.getCount() > 0) {
cursor.moveToFirst();
} else {
return null;
}
if (cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
if (!cursor.isClosed()) {
cursor.close();
}
Log.e("....contact name....", email + "\n" + contactName);
return contactName;
}
But it didn't help me as well.
EDIT-3:
public static String readContacts(Context context, String email) {
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(email));
Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
String contactName = null;
if(cursor!=null && cursor.getCount()>0 )
{
cursor.moveToFirst();
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}else{
return null;
}
if (!cursor.isClosed()) {
cursor.close();
}
Log.e("....contact name....", email + "\n" + contactName);
return contactName;
}
It didn't help me as well.
EDIT-4:
I tried
public String readContacts(Context context, String email) {
String name = null;
// define the columns I want the query to return
String[] projection = new String[]{
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup._ID};
// encode the email and build the filter URI
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(email));
// query time
Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
Log.e("....email.....", "Started uploadcontactphoto: Contact Found # " + email);
Log.e("....name....", "Started uploadcontactphoto: Contact name = " + name);
} else {
Log.e("....email exception....", "Contact Not Found # " + email);
}
cursor.close();
}
return name;
}
from https://stackoverflow.com/a/15007980/5738881 but didn't help as well.
Anybody got other way out?
EDIT-5:
public String readContacts() {
ContentResolver cr = getContentResolver();
#SuppressLint("Recycle")
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
String id, name = null, email = null;
if (cur != null && cur.getCount() > 0) {
while (cur.moveToNext()) {
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
System.out.println("name : " + name + ", ID : " + id);
// get the phone number
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
if (pCur != null) {
while (pCur.moveToNext()) {
String phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("phone" + phone);
}
}
if (pCur != null) {
pCur.close();
}
// get email and type
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
if (emailCur != null) {
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));
String emailType = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
System.out.println("Email " + email + " Email Type : " + emailType);
}
if (email == sEmail) {
sName = name;
}
}
if (emailCur != null) {
emailCur.close();
}
}
}
}
return name;
}
I tried above code instance from http://www.coderzheaven.com/2011/06/13/get-all-details-from-contacts-in-android/ and I am getting name, but it is different name than the email id owner.
So, tell me where I am going wrong..
And from above code snippet, I have also tried
if (email == sEmail) {
sName = name;
}
System.out.println("Email " + email + " Email Type : " + emailType);
}
}
if (emailCur != null) {
emailCur.close();
}
instead of
System.out.println("Email " + email + " Email Type : " + emailType);
}
if (email == sEmail) {
sName = name;
}
}
if (emailCur != null) {
emailCur.close();
}
but didn't help as well.
You should replace
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(email));
Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
with
Uri uri = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Email.CONTENT_FILTER_URI, Uri.encode(email));
Cursor cursor = cr.query(uri, new String[]{ContactsContract.CommonDataKinds.Email.CONTACT_ID,
ContactsContract.Data.DISPLAY_NAME}, null, null, null);
and then test it..
Always check getCount before use it.
if(cursor!=null && cursor.getCount()>0 )
{
cursor.moveToFirst();
}else{
return null;
}
Also check whether you have declared permission to read contact in manifest:
<uses-permission android:name="android.permission.READ_CONTACTS" />
You'll need a few other related permissions as well, look at the documentation for content to see which.
I suggested to try in this way and also debug your code using break point
where is the problem.
public static String readContacts(Context context, String email) {
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(email));
Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
String contactName = null;
if(cursor!=null && cursor.getCount()>0 )
{
cursor.moveToFirst();
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}else{
return null;
}
if (!cursor.isClosed()) {
cursor.close();
}
Log.e("....contact name....", email + "\n" + contactName);
return contactName;
}

Getting contactdetails from contact Id not working in android

Hello i am working on a contact directory,i have made a custom call logs,Noe i want to display the contact details when one of the contact is clicked,I have first fetched contact_id from the contact number,and then by searching over the internet i got a function to get all details from contact id,I have put it in my code,But its not working,not giving me results,
public void getDetials(String contactID) {
Uri myPhoneUri = Uri.withAppendedPath(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
Uri.encode(contactID));
// Query the table
#SuppressWarnings("deprecation")
Cursor phoneCursor = managedQuery(myPhoneUri, null, null, null, null);
// Get the phone numbers from the contact
for (phoneCursor.moveToFirst(); !phoneCursor.isAfterLast(); phoneCursor
.moveToNext()) {
// Get a phone number
String phoneNumber = phoneCursor
.getString(phoneCursor
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
//get name
String phonename = phoneCursor
.getString(phoneCursor
.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
//get email
String phoneemail = phoneCursor
.getString(phoneCursor
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Email.DATA));
//get image uri..!!
String img_uri = phoneCursor
.getString(phoneCursor
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
System.out
.println("=============my phone number ,is==================="
+ phoneNumber + "======in call info=="+"\n =========name is===="+phonename+"=================email is========"+phoneemail);
System.out.println("======myimgae url fopr the contact is============="+img_uri);
}
}
Here is method to read all phone numbers and emails for specified contact:
public void getContactDetails(int contactId) {
Log.d("Details", "---");
Log.d("Details", "Contact : " + contactId);
final Cursor phoneCursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.PHOTO_URI,
},
Data.CONTACT_ID + "=?",
new String[] {String.valueOf(contactId)}, null);
try {
final int idxAvatarUri = phoneCursor.getColumnIndexOrThrow(
ContactsContract.CommonDataKinds.Phone.PHOTO_URI);
final int idxName = phoneCursor.getColumnIndexOrThrow(
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
final int idxPhone = phoneCursor.getColumnIndexOrThrow(
ContactsContract.CommonDataKinds.Phone.NUMBER);
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(idxPhone);
String name = phoneCursor.getString(idxName);
String avatarUri = phoneCursor.getString(idxAvatarUri);
Log.d("Details", "Phone number: " + phoneNumber);
Log.d("Details", "Name: " + name);
Log.d("Details", "Avatar URI: " + avatarUri);
}
} finally {
phoneCursor.close();
}
final Cursor emailCursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.Email.ADDRESS,
},
Data.CONTACT_ID + "=?",
new String[] {String.valueOf(contactId)}, null);
try {
final int idxAddress = emailCursor.getColumnIndexOrThrow(
ContactsContract.CommonDataKinds.Email.ADDRESS);
while (emailCursor.moveToNext()) {
String address = emailCursor.getString(idxAddress);
Log.d("Details", "Email: " + address);
}
} finally {
emailCursor.close();
}
}
Please note that single contact can hold multiple phone numbers and emails.
Here is how to get all contacts details:
final Cursor cur = getContentResolver().query(Data.CONTENT_URI,
new String[]{Data.CONTACT_ID}, null, null, null);
try {
final int idxId = cur.getColumnIndex(Data.CONTACT_ID);
while (cur.moveToNext()) {
final int id = cur.getInt(idxId);
getContactDetails(id);
}
} finally {
cur.close();
}
Don't forget to add permission:
<uses-permission android:name="android.permission.READ_CONTACTS"/>

efficient way to load contacts with name and phone and picture with only one query

I have the following code to load all contacts with their phones and pictures on samsung s3 device.
public static void getAllContactWithNumberAndNameAndPhoto(Context context,
ArrayList<ContactInfo> mContactList, boolean starred) {
ContentResolver cr = context.getContentResolver();
Cursor cur = null;
if (starred == true) {
cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
"starred=?", new String[] { "1" }, null);
} else {
cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null,
null, null);
}
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
ContactInfo item = new ContactInfo();
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// Uri photo = PhoneUtils.getPhotoUriFromID(context, id);
String starredValue = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.STARRED));
boolean isFav = false;
if (starredValue.equals("1"))
isFav = true;
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 phoneNo = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
item.addPhone(removeCharactersFromPhoneNumber(phoneNo));
}
pCur.close();
// if (photo != null) {
//
// item.setPhoto(photo.toString());
// }
item.setName(name);
item.setFavorite(isFav);
item.setRecent(false);
mContactList.add(item);
}
}
cur.close();
}
}
when I run this code on 1000 contacts it takes about 40 second to load
when I remove the part of loading multiple phones for the same 1000 contact, it takes about 1.5 second.
Can any one tell me if there is an efficient way to load contacts phone and not let the user to wait all this time.
Try this:
private Cursor getContacts() {
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.PHOTO_URI, ContactsContract.Contacts.PHOTO_THUMBNAIL_URI, ContactsContract.CommonDataKinds.Phone.CONTENT_URI }; // put the items u need here
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return getContentResolver().query(uri, projection, selection, selectionArgs,
sortOrder);
}

Getting contact details takes too long in Android

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

Categories

Resources