我正在使用 ContentProvider 将数据插入 SQLiteDatabase 并且插入失败。我希望有人会看到我做错了什么。这是我的代码:
public Uri insert(Uri uri, ContentValues values) {
int uriType = sURIMatcher.match(uri);
if (uriType != ALLDATA) {
throw new IllegalArgumentException("Invalid URI for insert");
}
SQLiteDatabase sqlDB = mDB.getWritableDatabase();
try {
long newID = sqlDB.insertOrThrow(TABLE_BASEPATH,
null, values);
if (newID > 0) {
Uri newUri = ContentUris.withAppendedId(uri, newID);
getContext().getContentResolver().notifyChange(uri, null);
return newUri;
} else {
throw new SQLException("Failed to insert row into " + uri);
}
} catch (SQLiteConstraintException e) {
Log.i(DEBUG_TAG, "Ignoring constraint failure.");
}
return null;
}
mDB 是一个全局变量,设置如下:
private SQLData mDB;
SQLData 是我的数据库类的名称。当我在调试器中执行此代码时,它会验证 newID 是否大于 0 并进入 if 块。前两行执行(newUri 和 getContext() 等的赋值),但随后代码跳到底部并返回 null,而不是返回 newUri。有谁知道为什么?我看过这个线程,但它似乎不适用于我的情况。提前致谢!