SQLiteContentProviderImpl.insertInTransaction() bug
vit001 opened this issue · 1 comments
vit001 commented
This code is wrong:
@Override
protected Uri insertInTransaction(Uri uri, ContentValues values) {
long rowId = helper.insert(uri, values);
if (rowId > 0) {
Uri newUri = ContentUris.withAppendedId(uri, rowId);
notifyUriChange(newUri);
return newUri;
}
throw new SQLException("Failed to insert row into " + uri);
}
The Android documentation for android.database.sqlite.SQLiteDatabase.insert()
states:
@return the row ID of the newly inserted row, or -1 if an error occurred
This Android documentation is misleading, because a valid row ID can in fact be -1 or any other negative number. This happens when a table contains a single INTEGER PRIMARY KEY, in which case sqlite will use this key as row ID. For example:
CREATE TABLE tbl (id INTEGER NOT NULL, PRIMARY KEY (id) ON CONFLICT REPLACE);
INSERT INTO tbl(id) VALUES (-1);
The row ID of this row will be -1.
Your code should correctly read:
@Override
protected Uri insertInTransaction(Uri uri, ContentValues values) {
long rowId = helper.insert(uri, values);
Uri newUri = ContentUris.withAppendedId(uri, rowId);
notifyUriChange(newUri);
return newUri;
}
juankysoriano commented
Closing as this repository is no longer under maintenance and it's about to be archived