Search code examples
androidandroid-contentproviderandroid-contactsandroid-contentresolvercontactscontract

Get only sim and device stored Contacts


I want to display a list with the names (GIVEN_NAME, FAMILY_NAME) of contacts that are stored in the Device and in SIM (I want to exlcude Account contacts).

What I do now is:

1) I get all the Accounts in an accountTypesArray

2) I query RawContacts excluding the accounts

String where = ContactsContract.RawContacts.ACCOUNT_TYPE + " NOT IN (" + makePlaceholders(accountTypesArray.length) + ") "; String whereArgs[] = accountTypesArray;

return new CursorLoader(getActivity(), ContactsContract.RawContacts.CONTENT_URI, new String[]{ContactsContract.RawContacts._ID}, where, whereArgs, null);

3) I query DATA with mimeType structured name

String where = ContactsContract.Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE + "' AND " + ContactsContract.Data.RAW_CONTACT_ID + " IN (" + makePlaceholders(contactIDsArray.length) + ") ";

return new CursorLoader(getActivity(), ContactsContract.Data.CONTENT_URI, projection, where, contactIDsArray, SORT_ORDER);

The problem is when the contactIDsArray size is greater that 999 and SQLite throws too many SQL variables Exception. Is there a more efficient way?

Thank you in advance


Solution

  • This requires magic strings we've picked up from investigating different devices.

    For SIM contacts run the following query:

    String selection = RawContacts.ACCOUNT_TYPE + " IN ('vnd.sec.contact.sim', 'com.oppo.contacts.sim')";
    String[] projection = { RawContacts.CONTACT_ID, RawContacts.DISPLAY_NAME_PRIMARY };
    getContentResolver().query(RawContacts.CONTENT_URI, projection, selection, null, null);
    

    For device contacts, try the following:

    String selection = RawContacts.ACCOUNT_TYPE + " IN ('vnd.sec.contact.phone', 'com.htc.android.pcsc', 'com.sonyericsson.localcontacts', 'com.lge.sync', 'com.android.huawei.phone', 'Local Phone Account')";
    String[] projection = { RawContacts.CONTACT_ID, RawContacts.DISPLAY_NAME_PRIMARY };
    getContentResolver().query(RawContacts.CONTENT_URI, projection, selection, null, null);