无法更新数据库?

时间:2018-02-09 05:45:48

标签: android android-contentprovider

当我尝试更新数据时,我收到此错误

 java.lang.IllegalArgumentException: Update is not supported for content://com.example.recodedharran.booksinventory/books/3

我使用了调试器,匹配值似乎是-1!

    public int update(Uri uri, ContentValues contentValues, String selection,
                  String[] selectionArgs) {
    final int match = sUriMatcher.match(uri);
    switch (match) {
        case BOOKS:
            return updateBook(uri, contentValues, selection, selectionArgs);
        case BOOKS_ID:
            // For the PET_ID code, extract out the ID from the URI,
            // so we know which row to update. Selection will be "_id=?" and selection
            // arguments will be a String array containing the actual ID.
            selection = BooksContract.BooksEntry._ID + "=?";
            selectionArgs = new String[]{String.valueOf(ContentUris.parseId(uri))};
            return updateBook(uri, contentValues, selection, selectionArgs);
        default:
            throw new IllegalArgumentException("Update is not supported for " + uri);
    }
}
    private int updateBook(Uri uri, ContentValues values, String selection, String[] selectionArgs) {

    if (values.containsKey(BooksContract.BooksEntry.COLUMN_PRODUCT_NAME)) {
        String name = values.getAsString(BooksContract.BooksEntry.COLUMN_PRODUCT_NAME);
        if (name == null) {
            throw new IllegalArgumentException("Pet requires a name");
        }
        if (values.size() == 0) {
            return 0;
        }
    }
    SQLiteDatabase database = mDbHelper.getReadableDatabase();
    int rowsUpdated = database.update(BooksContract.BooksEntry.TABLE_NAME, values, selection, selectionArgs);
    // If 1 or more rows were updated, then notify all listeners that the data at the
    // given URI has changed
    if (rowsUpdated != 0) {
        getContext().getContentResolver().notifyChange(uri, null);
    }
    // Return the number of rows updated
    return rowsUpdated;
}

2 个答案:

答案 0 :(得分:1)

你在这里抛出这个例外。

        default:
        throw new IllegalArgumentException("Update is not supported for " + uri);

很明显match与两种情况下的值都不相等(BOOKS_IDBOOK

检查(BOOKS_IDBOOKS)是否始终满足switch语句或删除或更改

 default:
        throw new IllegalArgumentException("Update is not supported for " + uri);

 default: return -1; //return `-1` for example or any integer that gives a relevant indication.

答案 1 :(得分:0)

这是问题:]

    sUriMatcher.addURI(BooksContract.CONTENT_AUTHORITY, BooksContract.PATH_BOOKS + "#/", BOOK_ID);