Read contacts like native phone search do without fetching all contacts

Dhrupal
1 min readSep 29, 2016

--

You need to query in the contacts database using following query

Uri contentUri = Uri.withAppendedPath(
ContactsContract.Contacts.CONTENT_FILTER_URI,
Uri.encode(mSearchString));

Where mSearchString is the string you want to search

Projection for getting contacts is

private static String[] PROJECTION =
{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.LOOKUP_KEY,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY
};

Now take a cursor and do query on URI

cursor = contentResolver.query(contentUri, PROJECTION,null, null, null);
if (cursor != null) {
while (cursor != null && cursor.moveToNext()) {

contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY));

numbersAndEmails = new ArrayList<>();
numbers = new ArrayList<>();

//Get all phone nos associated with the id
cursorPhone = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + “ = “ + contactId, null, null);

if (cursorPhone != null) {
while (cursorPhone.moveToNext()) {
numbers.add(cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
cursorPhone.close();
}

//Get all emails associated with the id

emails = new ArrayList<>();
cursorEmail = contentResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + “ = ?”,
new String[]{contactId},
null);

if (cursorEmail != null) {
while (cursorEmail.moveToNext()) {
emails.add(cursorEmail.getString(cursorEmail.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)));
}
cursorEmail.close();

}
cursor.close();

--

--

Dhrupal

Passionate to try new, be better from yesterday, hold core values, help selflessly, be humble, embrace life at it’s awesome and at worst. JUST SHINE FOR SELF.