我在以前的项目中使用过 ContentProvider,这对我一直有效,但是这次我无法解决这个问题。当我使用内容解析器运行 update() 时,它会复制数据库中的对象而不是更新它。
这是触发更新的代码。它仅在 ContentValues 中包含所需的更新数据,而不是整个对象的重复。 where语句中的索引变量是对象在数据库中的行号,这个索引是正确的。
ContentValues cv = new ContentValues();
cv.put(MessageProvider.KEY_MESSAGE_STATUS, m.getStatus());
cr.update(MessageProvider.CONTENT_URI_MESSAGE, cv, MessageProvider.KEY_ID + "=" + index, null);
我不认为这段代码有问题,因为我已经尝试更改它,但它仍然会产生相同的重复。我的替代方案是在 Uri 中包含行索引。
这是内容提供者的代码。
@Override
public int update(Uri uri, ContentValues values, String where,
String[] whereArgs) {
int count = 0;
String whereString;
switch (uriMatcher.match(uri)) {
case MESSAGE:
count = messageDB.update(MESSAGE_TABLE, values, where, whereArgs);
break;
case MESSAGE_ID_:
String segment = uri.getPathSegments().get(1);
if (!TextUtils.isEmpty(where)) {
whereString = " AND (" + where + ')';
} else {
whereString = "";
}
count = messageDB.update(MESSAGE_TABLE, values, KEY_ID + "="
+ segment + whereString, whereArgs);
break;
default: throw new IllegalArgumentException("Unsupported URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
这里没有什么是不正确的,但我相信更多专家的眼睛将能够提供帮助!非常感谢!
最佳答案
我想到的是。
您是否已验证 where 子句是否正确并且它指向实际存在的记录。
当您有一个实际不存在的 where 子句时,messageDB.update 如何处理?
我自己没有使用过 ContentProviders。但这似乎是一个可能的错误来源。
关于java - Android ContentResolver.update() 产生重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11936138/