1

I need to find the contacts on a phone. Here's my code:

Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
    Cursor cursor = context.getContentResolver().query(
            uri,
            new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER,
                    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                    ContactsContract.CommonDataKinds.Phone._ID }, null,
            null,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
    cursor.moveToFirst();
    while (cursor.isAfterLast() == false) {
        String contactNumber = cursor
                .getString(cursor
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        String contactName = cursor
                .getString(cursor
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        int phoneContactID = cursor
                .getInt(cursor
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
        phoneContactInfo = new PhoneContactInfo();
        phoneContactInfo.setPhoneContactID(phoneContactID);
        phoneContactInfo.setContactName(contactName);
        phoneContactInfo.setContactNumber(contactNumber);
        if (phoneContactInfo != null) {
            arrContacts.add(phoneContactInfo);
        }
        phoneContactInfo = null;
        cursor.moveToNext();
    }

Is there a faster way to fetch the contacts?

Purag
  • 16,941
  • 4
  • 54
  • 75
  • 1
    What is the problem you are facing in this? – Lalit Poptani Aug 17 '12 at 04:52
  • `cursor.getColumnIndex(..)` - call this _once_ before your while-loop and reuse the value it returns. Also, you can reduce your while-statement conditions to `while(cursor.moveToNext())`, removing `cursor.moveToFirst()` and the `cursor.moveToNext()` you do at the end of the loop. – Jens Aug 17 '12 at 05:54

0 Answers0