Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch Delete items with Content Provider in Android

I'm trying to batch delete some items in a table.

    String ids = { "1", "2", "3" };

    mContentResolver.delete(uri, MyTables._ID + "=?", ids);

However I keep getting this following error

java.lang.IllegalArgumentException: Too many bind arguments. 3 arguments were provided but the statement needs 1 arguments.

like image 284
Frank Sposaro Avatar asked Jul 12 '12 18:07

Frank Sposaro


2 Answers

You can use ContentProviderOperation for batch deletion/insertion/update in one transaction. It's much nicer you don't have to concatenate strings. It also should be very efficient. For deletion:

    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
    ContentProviderOperation operation;

    for (Item item : items) {

        operation = ContentProviderOperation
                .newDelete(ItemsColumns.CONTENT_URI)
                .withSelection(ItemsColumns.UID + " = ?", new String[]{item.getUid()})
                .build();

        operations.add(operation);
    }

    try {
        contentResolver.applyBatch(Contract.AUTHORITY, operations);
    } catch (RemoteException e) {

    } catch (OperationApplicationException e) {

    }
like image 199
X.Y. Avatar answered Sep 18 '22 09:09

X.Y.


The error occurs because you have a single placeholder (?) in your where clause, while you pass three arguments. You should do:

String ids = { "1", "2", "3" };

mContentResolver.delete(uri, MyTables._ID + "=? OR " + MyTables._ID + "=? OR " + MyTables._ID + "=?", ids);

I do not know if SQLite supports the IN clause, if so you could also do:

String ids = { "1, 2, 3" };

mContentResolver.delete(uri, MyTables._ID + " IN (?)", ids);
like image 44
Jan-Henk Avatar answered Sep 19 '22 09:09

Jan-Henk