Search code examples
androiddatabasecursor

Correct build cursor query with selection args android sqlite


Try to build correct query to get raw contacts from android database. Have a query:

 String select = new StringBuilder( ContactsContract.RawContacts.CONTACT_ID + " = ? " + QUERY_AND_VALUE + stringBuilderTypeLocalContactSelection.toString() ).toString();
 cursor = context.getContentResolver().query( ContactsContract.RawContacts.CONTENT_URI, columnSelection,select,new String[]{ String.valueOf( contactId ) }, null );

where stringBuilderTypeLocalContactSelection is:

 private static final StringBuilder stringBuilderTypeLocalContactSelection = new StringBuilder( ContactsContract.RawContacts.ACCOUNT_TYPE + " <> 'com.anddroid.contacts.sim'" +
            QUERY_AND_VALUE + ContactsContract.RawContacts.ACCOUNT_TYPE + " <> 'com.google' " + " AND " + ContactsContract.RawContacts.ACCOUNT_TYPE
            + " <> 'com.android.contacts.sim' " + QUERY_AND_VALUE + ContactsContract.RawContacts.ACCOUNT_TYPE + " <> 'vnd.sec.contact.sim' "
            + QUERY_AND_VALUE + ContactsContract.RawContacts.ACCOUNT_TYPE + " <> 'com.viber.voip.account'" + QUERY_AND_VALUE + ContactsContract.RawContacts.DELETED + " = 0 " );

In this query try to get raw contacts with types, which not described in string builder, but if ACCOUNT_TYPE value is null, cursor is not take record from database. Is it possible to make a valid selection when ACCOUNT_TYPE = null and cursor give me record too?


Solution

  • I had the same problem. I wanted to get contacts, that are not "viber" and "whatsapp", but the cursor didn't take records with null ACCOUNT_TYPE. My decision was to add " OR " + ContactsContract.RawContacts.ACCOUNT_TYPE + " IS NULL" to the selection and this solved the problem.