【问题标题】:Content provider updating all rows内容提供者更新所有行
【发布时间】:2012-03-29 20:38:15
【问题描述】:

在内容提供商上工作,但我遇到了问题。当我尝试通过内容提供程序更新 SQLite 数据库中的某一行时,它会更新所有行中的列,而不仅仅是我指定的行。我知道 CP 正在工作,因为我可以访问它,用它填充列表视图,并更改列的内容,但不能只更改一列。

这里是相关的更新方法

public int update(Uri url, ContentValues values, String where,
            String[] whereArgs) {
        SQLiteDatabase mDB = dbHelper.getWritableDatabase();
        int count;
        String segment = "";
        switch (URL_MATCHER.match(url)) {
        case ITEM:
            count = mDB.update(TABLE_NAME, values, where, whereArgs);
            break;
        case ITEM__ID:
            segment = url.getPathSegments().get(1);
            count = mDB.update(TABLE_NAME, values,
                    "_id="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URL " + url);
        }
        getContext().getContentResolver().notifyChange(url, null);
        return count;
    }

这是我用来(尝试)更新它的代码。

ContentValues mUpdateValues = new ContentValues();

mUpdateValues.put(ContentProvider.HAS, "true");
mUpdateValues.put(ContentProvider.WANT, "false");

mRowsUpdated = getContentResolver().update(Uri.parse(ContentProvider._ID_FIELD_CONTENT_URI
+ rowId), mUpdateValues, null, null);

这里是 URI

URL_MATCHER.addURI(AUTHORITY, TABLE_NAME + "/#", ITEM__ID);

谢谢,任何帮助将不胜感激。

编辑我也试过了

mRowsUpdated = getContentResolver().update(
                    ContentProvider._ID_FIELD_CONTENT_URI, mUpdateValues,
                    null, null);

mRowsUpdated = getContentResolver().update(
                    ContentProvider.CONTENT_URI, mUpdateValues,
                    null, null);

【问题讨论】:

    标签: android sqlite android-contentprovider


    【解决方案1】:

    您没有指定 WHERE 子句,该子句仅用于更新特定行。内容提供者的默认行为是更新所有行,除非您指定条件。

    来自文档: developer.android.com/reference/android/content/ContentResolver.html

    Parameters
    uri     The URI to modify.
    values  The new field values. The key is the column name for the field. A null value will remove an existing field value.
    where   A filter to apply to rows before updating, formatted as an SQL WHERE clause (excluding the WHERE itself).
    

    【讨论】:

    • 我尝试过使用rowId,它是一个基于要更新记录的_id 的字符串。我也试过将它解析为long,如 WHERE _id = 'rowId'`
    • 好的,让它工作,因为你是唯一的答案,而且基本上是正确的,因为我的WHERE 声明被搞砸了,我将你的标记为正确。谢谢。
    • @BillGary 为了完整起见,请使用最终有效的解决方案更新您的问题。谢谢。
    猜你喜欢
    • 2018-10-11
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多