ContentProvider update() 不起作用



update()方法的实现可能有问题,但我不确定是什么:

 @Override
 public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) {
        int count = 0;
        switch (uriMatcher.match(uri)) {
            case uriCode:
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
 }

以下是我调用该方法的方式:

Random r1 = new Random();
long insertValue1 = r1.nextInt(5);
updatedValues.put(Provider.adPoints, insertValue1);
int value = getContentResolver().update(Provider.CONTENT_URI, updatedValues, null, null); //insert(Provider.CONTENT_URI, values);

我还想利用count并返回update()中更新的行数。这里似乎有什么问题?

Switch 中没有更新代码。我想你错过了

为了使用内容提供程序获取行更新,您必须执行以下操作:

首先,请确保在 ContentProvider 中具有 DatabaseHelper 类的引用:

private YourDatabaseSQLLiteHelper mDbHelper;
@Override
public boolean onCreate() {
    mDbHelper = new YourDatabaseSQLLiteHelper(getContext());
    return true;
}

然后覆盖内容提供程序上的 update(( 方法:

@Override
public int update(@NonNull Uri uri, @Nullable ContentValues cv, @Nullable String selection, @Nullable String[] selectionArgs) {
    int rowsUpdated;
    switch (sUriMatcher.match(uri)) {
        case YOUR_TABLE_CODE:
            // This is what you need.
            rowsUpdated = mDbHelper.getWritableDatabase().update(
                    YourTableContract.YourTableEntry.TABLE_NAME,
                    cv,
                    selection,
                    selectionArgs);
            break;
        default:
            throw new UnsupportedOperationException("Unknown uri: " + uri);
    }
    if (rowsUpdated != 0)
        getContext().getContentResolver().notifyChange(uri, null);
    return rowsUpdated;
}

然后,当您调用该方法时,它必须返回更新的行数。

int rowsUpdatedCount = getContentResolver().update(...);

请让我知道这是否适合您。

相关内容

最新更新