Batch Delete items with Content Provider in Android

别来无恙 提交于 2019-11-30 18:56:08

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);

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) {

    }
String sqlCommand = String.format("DELETE FROM %s WHERE %s IN (%s);", TABLE_NAME, KEY_ID, 1,2,3);

db.execSQL(sqlCommand);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!