Loading contacts fast From Android Contacts ContentProvider .





For loading the contacts fast from the content provider we need to provide the projection while querying the contacts cursor



Important Cursors:

Type 1: ContactsContract.CommonDataKinds.Phone.CONTENT_URI

Type2:   ContactsContract.Contacts.CONTENT_URI


We will be using the type 1 cursor for getting the name,number of the user.
void getAllContacts() {
        long startnow;
        long endnow;
        
        startnow = android.os.SystemClock.uptimeMillis();
        ArrayList arrContacts = new ArrayList();
        
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER;
        Cursor cursor = ctx.getContentResolver().query(uri, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER,   ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.Contacts._ID}, selection, 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));
            int contactID = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Log.d("con ", "name " + contactName + " " + " PhoeContactID " + phoneContactID + "  ContactID " + contactID)

            cursor.moveToNext();
        }
        cursor.close();
        cursor = null;

        endnow = android.os.SystemClock.uptimeMillis();
        Log.d("END", "TimeForContacts " + (endnow - startnow) + " ms");
    }



The above method will give the list of contacts along with time taken to load the details.
in my case i have 500 contacts in my phonebook which takes 470ms (less than half second).








100 Bestselling Courses-The Complete Android Developer Course - Build 14 Apps
Post a Comment