In my app, when launched I would like to display all the contacts with search filter option. I have achieved this but the problem is – while loading the contacts, it takes more time. How can I improve the efficiency of the code ? Below code snippet shows how I am retreiving contacts:
public ContactList newContactList(Context ctx)
{
ContactList contacts = new ContactList();
String id = "";
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
try
{
this.cur = this.cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, sortOrder);
if (this.cur.getCount() > 0) {
while (cur.moveToNext()) {
Contact c = new Contact();
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
c.setId(id);
c.setDisplayName(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
c.setPhone(this.getPhoneNumbers(ctx, id));
c.setEmail(this.getEmailAddresses(id));
c.setNotes(this.getContactNotes(id));
c.setAddresses(this.getContactAddresses(id));
c.setImAddresses(this.getIM(id));
c.setOrganization(this.getContactOrg(id));
//c.setPicture(loadContactPhoto(cr, cur.getLong(cur.getColumnIndex(CommonDataKinds.Photo.CONTACT_ID))));
contacts.addContact(c);
}
}
}
}
catch(Exception e)
{
throw new IllegalStateException(e);
}
finally
{
cur.close();
}
return(contacts);
}
ContactList is a class that returns ArrayList of all contacts, and with this arraylist I am setting it to my custom adapter class. I guess, because of fetching arraylist by itereating through cursor is taking much time. But, I would need this arraylist to filter the contacts based on search criteria and to display the custom contact list. Is there any way that I can improve the performance of the code?
Why don’t you use CursorAdapter ?
http://developer.android.com/reference/android/widget/CursorAdapter.html