【问题标题】:Batch Delete items with Content Provider in Android在 Android 中使用 Content Provider 批量删除项目
【发布时间】:2012-07-12 18:55:23
【问题描述】:

我正在尝试批量删除表格中的一些项目。

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

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

但是我不断收到以下错误

java.lang.IllegalArgumentException:绑定参数过多。提供了 3 个参数,但该语句需要 1 个参数。

【问题讨论】:

    标签: android android-contentprovider android-contentresolver


    【解决方案1】:

    您可以在一个事务中使用ContentProviderOperation 进行批量删除/插入/更新。不必连接字符串要好得多。它也应该非常有效。删除:

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

    【讨论】:

    • 正确,我有这个疑问 BulkInsert 是否比 ApplyBatch 更快
    • 对于短信操作的授权是"sms"
    • 对于歌曲操作,AUTHORITY id 'MediaStore.AUTHORITY'
    【解决方案2】:

    发生错误是因为您在 where 子句中有一个占位符 (?),而您传递了三个参数。你应该这样做:

    String ids = { "1", "2", "3" };
    
    mContentResolver.delete(uri, MyTables._ID + "=? OR " + MyTables._ID + "=? OR " + MyTables._ID + "=?", ids);
    

    不知道SQLite是否支持IN子句,如果支持也可以:

    String ids = { "1, 2, 3" };
    
    mContentResolver.delete(uri, MyTables._ID + " IN (?)", ids);
    

    【讨论】:

    • 谢谢 Jan。我想我对 selectionArgs 的工作方式有一个根本的误解。我的 id 的大小可以是可变的。所以你的第二个解决方案看起来更有吸引力。但是,恐怕这似乎也不起作用。我想我可以检查我的大小和循环来构造 where 类,但这看起来不太好:(
    【解决方案3】:
    String sqlCommand = String.format("DELETE FROM %s WHERE %s IN (%s);", TABLE_NAME, KEY_ID, 1,2,3);
    
    db.execSQL(sqlCommand);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-19
      • 2019-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      • 2012-01-08
      • 1970-01-01
      相关资源
      最近更新 更多