Reputation: 1152
I'm working on an app which reads the phone contacts and displays them in the form of list. I have to send message to selected contacts from the list. But the problem is that the app gets hanged if the mobile has more than 500 contacts. I don't get where the problem is..
I found this code on internet and implemented in my app. Contacts will be displayed but after taking so much time. Here is my code
ContentResolver cr = getActivity().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._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur =
cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +"=?",
new String[]{id}, null);
while (pCur.moveToNext()) {
int phoneType = pCur.getInt(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.TYPE));
String phoneNumber = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
switch (phoneType) {
case Phone.TYPE_MOBILE:
Log.e(name + "(mobile number)", phoneNumber);
break;
case Phone.TYPE_HOME:
Log.e(name + "(home number)", phoneNumber);
break;
case Phone.TYPE_WORK:
Log.e(name + "(work number)", phoneNumber);
break;
case Phone.TYPE_OTHER:
Log.e(name + "(other number)", phoneNumber);
break;
default:
break;
}
}
pCur.close();
}
} }
Upvotes: 1
Views: 61
Reputation: 145
it is due to heavy task in UI
thread that blocks UI
, Use AyncTask
for this purpose.
Upvotes: 0
Reputation: 3584
To read contacts -
private void fetchContacts() {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (name == null || name.equals(""))
name = phoneNumber;
if (Utils.notNull(phoneNumber)) {
phoneNumber = Utils.checkAndWrapMobileNumber(getApplicationContext(), phoneNumber);
allContacts.put(phoneNumber, name);
contactList.add(phoneNumber);
}
}
phones.close();
}
And better to use this code in AssyncTask so read in background thread.
Hope it will help you :)
Upvotes: 2