Batch Delete items with Content Provider in Android

后端 未结 3 1780
长发绾君心
长发绾君心 2021-01-04 19:40

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

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

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


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-04 20:28

    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 operations = new ArrayList();
        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) {
    
        }
    

提交回复
热议问题