Search code examples
androidandroid-cursorandroid-cursorloader

Querying the ContentProvider for certain IDs


I have a contacts table and I need to get only certain IDs.

Imagine I have 10 contacts with ids from 1 to 10 and I want to get a Cursor with contacts 1 and 2.

A working code would be:

new CursorLoader(MyContentProvider.CONTACT_CONTENT_URI, null,
MyContentProvider.CONTACT_COLUMN_ID + " IN  ( 1, 2 )",
null, null);

My problem is that I am unable to use the selectionArgs parameter since the escaping would break the query.

Can you think of a way of using the selectionArgs parameters and making this work?


Solution

  • If you want to use selectionArgs you can only use it like

    String selection = "column IN (?, ?, ?)";
    String[] selectionArgs = { "1", "2", "3" };
    

    You need to build the "( ?, ?, ? )" string based on the number of arguments at runtime though. E.g.

    private static String getSelection(int args) {
        StringBuilder sb = new StringBuilder(MyContentProvider.CONTACT_COLUMN_ID + " IN  (");
        boolean first = true;
        for (int i = 0; i < args; i ++) {
            if (first) {
                first = false;
            } else {
                sb.append(',');
            }
            sb.append('?');
        }
        sb.append(')');
        return sb.toString();
    }