Contact fetching takes too much time - android

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

Related

Not able to get all contacts due to too much work on main thread

I am trying to store all contacts in a String array, but it's not getting all contacts due to the following error:
I/Choreographer: Skipped 213 frames! The application may be doing too much work on its main thread.
Java Code
private void getContactList() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if ((cur != null ? cur.getCount() : 0) > 0) {
progressDialog.show();
while (cur != null && cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
if (cur.getInt(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));
// Log.i("tag", "Name: " + name);
// Log.i("tag", "Phone Number: " + phoneNo);
myname += name + ",";
mynumber += phoneNo + ",";
}
pCur.close();
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
Log.i("tag", "Name: " + myname + mynumber);
}
if (cur != null) {
cur.close();
}
}
you need to fetch the contact in a background thread.
private class FetchContacts extends AsyncTask<Void, Void,
ArrayList<Contact>> {
private final String DISPLAY_NAME = Build.VERSION.SDK_INT >=
Build.VERSION_CODES.HONEYCOMB ?
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY :
ContactsContract.Contacts.DISPLAY_NAME;
private final String FILTER = DISPLAY_NAME + " NOT LIKE '%#%'";
private final String ORDER = String.format("%1$s COLLATE NOCASE",
DISPLAY_NAME);
#SuppressLint("InlinedApi")
private final String[] PROJECTION = {
ContactsContract.Contacts._ID,
DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER
};
#Override
protected ArrayList<LearnSaveContact> doInBackground(Void... params) {
try {
ArrayList<Contact> contacts = new ArrayList<>();
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,
PROJECTION, FILTER, null, ORDER);
if (cursor != null && cursor.moveToFirst()) {
do {
// get the contact's information
String id =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
Integer hasPhone = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
// get the user's email address
String email = null;
Cursor ce = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{id}, null);
if (ce != null && ce.moveToFirst()) {
email = ce.getString(ce.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
ce.close();
}
// get the user's phone number
String phone = null;
if (hasPhone > 0) {
Cursor cp = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
if (cp != null && cp.moveToFirst()) {
phone = cp.getString(cp.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
cp.close();
}
}
// if the user user has an email or phone then add it to contacts
if ((!TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()
&& !email.equalsIgnoreCase(name)) || (!TextUtils.isEmpty(phone))) {
Contact contact = new Contact();
contact.name = name;
contact.email = email;
contact.phoneNumber = phone;
contacts.add(contact);
}
} while (cursor.moveToNext());
// clean up cursor
cursor.close();
}
return contacts;
} catch (Exception ex) {
return null;
}
}
#Override
protected void onPostExecute(ArrayList<Contact> contacts) {
if (contacts != null) {
// success
mContacts = contacts;
} else {
// show failure
// syncFailed();
}
}
}
public class Contact{
public String name;
public String email;
public String phoneNumber;
public Contact() {}
}
Try this:
this.runOnUiThread(new Runnable() {
public void run() {
private void getContactList() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if ((cur != null ? cur.getCount() : 0) > 0) {
progressDialog.show();
while (cur != null && cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
if (cur.getInt(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));
// Log.i("tag", "Name: " + name);
// Log.i("tag", "Phone Number: " + phoneNo);
myname += name + ",";
mynumber += phoneNo + ",";
}
pCur.close();
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
Log.i("tag", "Name: " + myname + mynumber);
}
if (cur != null) {
cur.close();
}
}
}});

get All Contacts from Mobile android

I want to get all contact number from mobile
I am using the following code but it is giving only contact numbers which are in mobile not of sim
private void getContactList() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if ((cur != null ? cur.getCount() : 0) > 0) {
while (cur != null && cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
if (cur.getInt(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));
ContactsPlacer obj = new ContactsPlacer();
obj.setContactname(name);
obj.setContactnumber(phoneNo);
names.add(obj);
}
pCur.close();
}
}
}
if(cur!=null){
cur.close();
}
}
Below is code for getting all contact from device
private void getAllContacts() {
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Read Contact permission not enabled", Toast.LENGTH_SHORT).show();
}
else {
contactVOList = new ArrayList();
ContactVO contactVO;
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));
contactVO = new ContactVO(pref.getUser_ID(),phoneNumberArrayList);
contactVO.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));
phoneNumber = phoneNumber.replace(" ", "");
phoneNumber = phoneNumber.trim();
String number = "+91#1234*121#";
number=phoneNumber.replaceAll("[\\D]", "");
contactVO.setContactNumber(number);
phoneNumberArrayList.add(number);
}
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));
}
emailCursor.close();
contactVOList.add(contactVO);
}
}
cursor.close();
if (contactVOList.size() > 0) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
CallAPI();
}
}, 1000);
}
}
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
and Added below code for get SIM contact
Uri simUri = Uri.parse("content://icc/adn");Cursor cursorSim = this.getContentResolver().query(simUri, null, null,null, null);
while (cursorSim.moveToNext()) {
listName.add(cursorSim.getString(cursorSim.getColumnIndex("name")));
listContactId.add(cursorSim.getString(cursorSim.getColumnIndex("_id")));
listMobileNo.add(cursorSim.getString(cursorSim.getColumnIndex("number")));
}

Android: how do I get a number from Contacts by email?

My goal is to get the phone number and the e-mail of a contact.
I've tried to use one cursor but somehow it returns the same thing for phone and e-mail (either of the two, depending on tweaking some things). What I want right now is a hashtable that maps e-mails to phone numbers, or two hashtables, emailToID, and IDToPhone. This is what I have so far, but the IDs I use are not the same accross parameters (the a#a.com's phone is 123, their respective IDs are not the same and cannot be easily mapped). Would be grateful for help!
public String getPhoneByEmail(String userEmail){
final String EMAIL_URI = ContactsContract.CommonDataKinds.Email.DATA;
final String PHONE_URI = ContactsContract.CommonDataKinds.Phone.NUMBER;
Hashtable<String, Integer> emailToId = new Hashtable<>();
Hashtable<Integer, String> idToPhone = new Hashtable<>();
ContentResolver cr = getContext().getContentResolver();
Cursor cur1 = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
null,
null, null);
Cursor cur2 = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
null,
null, null);
while (cur1.moveToNext()) {
String phone = cur1.getString(cur1.getColumnIndex(PHONE_URI));
String id1 = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
idToPhone.put(Integer.parseInt(id1), phone);
}
while (cur2.moveToNext()) {
String email = cur2.getString(cur2.getColumnIndex(EMAIL_URI));
String id2 = cur2.getString(cur2.getColumnIndex(ContactsContract.CommonDataKinds.Email._ID));
emailToId.put(email, Integer.parseInt(id2));
}
cur1.close();
cur2.close();
if (emailToId.get(userEmail)!=null){
int id = emailToId.get(userEmail);
int newId = id - 2;
String phone = idToPhone.get(newId);
return phone;
}
else return "not found";
}
Got it with help from this: https://stackoverflow.com/a/4154729/6463084
private String getPhoneByEmail(String userEmail) {
Hashtable<String, String> emailToId = new Hashtable<>();
Hashtable<String, String> idToPhone = new Hashtable<>();
ContentResolver cr = getContext().getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1"))
hasPhone = "true";
else
hasPhone = "false";
if (Boolean.parseBoolean(hasPhone)) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
idToPhone.put(contactId, phoneNumber);
}
phones.close();
}
Cursor emails = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null);
while (emails.moveToNext()) {
String emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
emailToId.put(emailAddress, contactId);
}
emails.close();
}
cursor.close();
if (emailToId.get(userEmail) != null) {
String id = emailToId.get(userEmail);
if (idToPhone.get(id) != null) {
String phone = idToPhone.get(id);
return phone;
}
}
return "not found";
}
Try this code to Read Contact Number/Name/Email From Phone..
public void storeContactsInLocal() {
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
// retrieve all contacts as a cursor.
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, sortOrder);
//now we have cusror with contacts and get diffrent value from cusror.
String lastNumber = null;
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String email = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String number = phoneNumber.replaceAll("\\s+", "");
if (!number.equals(lastNumber)) {
lastNumber = number;
try {
// Save Contact in Database!
String contactDetail = "Name :" + name + " : " + "Number :" + number+ " : " + "Email :" + email;
Log.e("Contact :", contactDetail);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Now call this Function from Your Activity like..
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
storeContactsInLocal();
}
});
t.start();
}
}, 100);
Just don't forget to ask/Add Permission to read Contacts!

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

How to get all contacts first name, last name, email, phone number, etc without duplicates

I am trying to get details of all the contacts available in phone contacts using below code. But facing small issue of duplicate values.
EDITED
ACTUAL CODE STARTS :-
private String refreshData() {
String emaildata = "";
try {
ContentResolver cr = getBaseContext().getContentResolver();
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP
+ " = '" + ("1") + "'";
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
Cursor cur = cr
.query(ContactsContract.Contacts.CONTENT_URI,
null,
selection
+ " AND "
+ ContactsContract.Contacts.HAS_PHONE_NUMBER
+ "=1", null, sortOrder);
if (cur.getCount() > 0) {
Log.i("Content provider", "Reading contact emails");
while (cur.moveToNext()) {
mContactSet.add(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID)));
}
} else {
emaildata += "Data not found.";
}
cur.close();
Log.i(TAG, "Total contacts = " + mContactSet.size());
Iterator<String> iterator = mContactSet.iterator();
while (iterator.hasNext()) {
String contactId = iterator.next();
Log.i(TAG, "ID ==> " + contactId);
// Create query to use CommonDataKinds classes to fetch
// emails
Cursor emails = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = " + contactId, null, null);
// Name
String whereName = ContactsContract.Data.MIMETYPE
+ " = ? AND "
+ ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID
+ " = ?";
String[] whereNameParams = new String[] {
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE,
contactId };
Cursor nameCur = cr
.query(ContactsContract.Data.CONTENT_URI,
null,
whereName,
whereNameParams,
ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
while (nameCur.moveToNext()) {
String given = nameCur
.getString(nameCur
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
String family = nameCur
.getString(nameCur
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
String display = nameCur
.getString(nameCur
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
Log.i(TAG, "First Name ==> " + given);
Log.i(TAG, "Last Name ==> " + family);
Log.i(TAG, "Display ==> " + display);
}
nameCur.close();
}
} catch (Exception e) {
emaildata += "Exception : " + e + "";
}
return emaildata;
}
Modified the query and get some better results but still the issue is same for some of the contacts and getting repeat values.
UPDATE :- I have used HashSet to get unique contact id and which I successfully get as well, but when I am getting the names from contact id I am getting the same value for 2-3 times for some of the contacts. I am very much confused that how this is possible that same contact is stored 2-3 times with same id?
DO I NEED TO USE HASHSET FOR FIRST NAME, LAST NAME, PHONE NUMBER, EMAIL, ETC? IS THERE ANY OTHER WAY?
This is the complete solution
public ArrayList<HashMap<String, Object>> getContacts() {
ArrayList<HashMap<String, Object>> contacts = new ArrayList<HashMap<String, Object>>();
final String[] projection = new String[] { RawContacts.CONTACT_ID, RawContacts.DELETED };
#SuppressWarnings("deprecation")
final Cursor rawContacts = managedQuery(RawContacts.CONTENT_URI, projection, null, null, null);
final int contactIdColumnIndex = rawContacts.getColumnIndex(RawContacts.CONTACT_ID);
final int deletedColumnIndex = rawContacts.getColumnIndex(RawContacts.DELETED);
if (rawContacts.moveToFirst()) {
while (!rawContacts.isAfterLast()) {
final int contactId = rawContacts.getInt(contactIdColumnIndex);
final boolean deleted = (rawContacts.getInt(deletedColumnIndex) == 1);
if (!deleted) {
HashMap<String, Object> contactInfo = new HashMap<String, Object>() {
{
put("contactId", "");
put("name", "");
put("email", "");
put("address", "");
put("photo", "");
put("phone", "");
}
};
contactInfo.put("contactId", "" + contactId);
contactInfo.put("name", getName(contactId));
contactInfo.put("email", getEmail(contactId));
contactInfo.put("photo", getPhoto(contactId) != null ? getPhoto(contactId) : "");
contactInfo.put("address", getAddress(contactId));
contactInfo.put("phone", getPhoneNumber(contactId));
contactInfo.put("isChecked", "false");
contacts.add(contactInfo);
}
rawContacts.moveToNext();
}
}
rawContacts.close();
return contacts;
}
private String getName(int contactId) {
String name = "";
final String[] projection = new String[] { Contacts.DISPLAY_NAME };
final Cursor contact = managedQuery(Contacts.CONTENT_URI, projection, Contacts._ID + "=?", new String[] { String.valueOf(contactId) }, null);
if (contact.moveToFirst()) {
name = contact.getString(contact.getColumnIndex(Contacts.DISPLAY_NAME));
contact.close();
}
contact.close();
return name;
}
private String getEmail(int contactId) {
String emailStr = "";
final String[] projection = new String[] { Email.DATA, // use
// Email.ADDRESS
// for API-Level
// 11+
Email.TYPE };
final Cursor email = managedQuery(Email.CONTENT_URI, projection, Data.CONTACT_ID + "=?", new String[] { String.valueOf(contactId) }, null);
if (email.moveToFirst()) {
final int contactEmailColumnIndex = email.getColumnIndex(Email.DATA);
while (!email.isAfterLast()) {
emailStr = emailStr + email.getString(contactEmailColumnIndex) + ";";
email.moveToNext();
}
}
email.close();
return emailStr;
}
private Bitmap getPhoto(int contactId) {
Bitmap photo = null;
final String[] projection = new String[] { Contacts.PHOTO_ID };
final Cursor contact = managedQuery(Contacts.CONTENT_URI, projection, Contacts._ID + "=?", new String[] { String.valueOf(contactId) }, null);
if (contact.moveToFirst()) {
final String photoId = contact.getString(contact.getColumnIndex(Contacts.PHOTO_ID));
if (photoId != null) {
photo = getBitmap(photoId);
} else {
photo = null;
}
}
contact.close();
return photo;
}
private Bitmap getBitmap(String photoId) {
final Cursor photo = managedQuery(Data.CONTENT_URI, new String[] { Photo.PHOTO }, Data._ID + "=?", new String[] { photoId }, null);
final Bitmap photoBitmap;
if (photo.moveToFirst()) {
byte[] photoBlob = photo.getBlob(photo.getColumnIndex(Photo.PHOTO));
photoBitmap = BitmapFactory.decodeByteArray(photoBlob, 0, photoBlob.length);
} else {
photoBitmap = null;
}
photo.close();
return photoBitmap;
}
private String getAddress(int contactId) {
String postalData = "";
String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] addrWhereParams = new String[] { String.valueOf(contactId), ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };
Cursor addrCur = managedQuery(ContactsContract.Data.CONTENT_URI, null, addrWhere, addrWhereParams, null);
if (addrCur.moveToFirst()) {
postalData = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
}
addrCur.close();
return postalData;
}
private String getPhoneNumber(int contactId) {
String phoneNumber = "";
final String[] projection = new String[] { Phone.NUMBER, Phone.TYPE, };
final Cursor phone = managedQuery(Phone.CONTENT_URI, projection, Data.CONTACT_ID + "=?", new String[] { String.valueOf(contactId) }, null);
if (phone.moveToFirst()) {
final int contactNumberColumnIndex = phone.getColumnIndex(Phone.DATA);
while (!phone.isAfterLast()) {
phoneNumber = phoneNumber + phone.getString(contactNumberColumnIndex) + ";";
phone.moveToNext();
}
}
phone.close();
return phoneNumber;
}
How to use?
ArrayList<HashMap<String, Object>> contactList = getContacts();
System.out.println("Contact List : " +contactList);
Output:
[
{
phone=992-561-1618;848-807-4440;,
contactId=1,
photo=android.graphics.Bitmap#44f40aa0,
address=Zalavadia Strret
Manavadar, Gujarat 362630
India,
email=birajzalavadia#gmail.com;biraj#tasolglobal.com;,
name=Biraj Zalavadia
},
{
phone=992-511-1418;842-827-4450;,
contactId=2,
photo=android.graphics.Bitmap#44f40aa0,
address=Makadiya Strret
Junagadh, Gujarat 364890
India,
email=niles#gmail.com;niles#tasolglobal.com;,
name=Niles patel
}
.......
]
NOTE:
You will get phone and email semicolon(;) separated if its more than one.

Categories

Resources