Android,处理 SQLiteConstraintException
我在 Android 中有这个方法:
public void insertarTitulo(String _id, String title, String url){
ContentValues cv = new ContentValues();
cv.put("_id", _id);
cv.put("title", title);
cv.put("URL", url);
try{
getWritableDatabase().insert("book", "book", cv);
}catch(SQLiteConstraintException e){
Log.e(MyActivity.LOGTAG, "This code doesn't show");
}
close();
}
title 值是唯一的,因此当我插入重复值时会抛出约束错误,到目前为止这是正确的。 一切都按预期进行。 但我无法使 catch 代码起作用。
I've got this method in Android:
public void insertarTitulo(String _id, String title, String url){
ContentValues cv = new ContentValues();
cv.put("_id", _id);
cv.put("title", title);
cv.put("URL", url);
try{
getWritableDatabase().insert("book", "book", cv);
}catch(SQLiteConstraintException e){
Log.e(MyActivity.LOGTAG, "This code doesn't show");
}
close();
}
title value is unique so when I insert a duplicate value throws me the Constraint error, so far that's correct.
Everything works as expected.
but I can't make the catch code work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用 插入或抛出。否则,如果发生错误,insert 仅返回 -1。
Try using insertOrThrow. Otherwise, insert just returns -1 in the event of an error.
当执行从入口类添加数据库中的值时添加boolean来控制数据
例如:
在 DBhelper 类中:
如果传递的值没有冲突或错误,则这里的数据库将尝试添加值,如果发生错误,布尔值将保持为 true,则布尔值将为 false 并将返回它,并且您可以将任何消息作为 ex toast (有冲突)
When you execute to add the values in the database from the entry class add boolean to control the data
ex:
in the DBhelper Class :
The database here will try to add the values if the values passed without conflict or error the boolean will remain true if error the boolean will be false and will return it and you can toast any message as ex toast (there is a conflict)
抱歉,上面提到的答案在 android 4.4.2 上不适用于我。
最小 sdk 级别 11,最大 21。
对我有用的是以下内容:
这正确捕获了约束,并且您可以在 catch 块内进行处理。
RR。
Sorry but the answers mentioned above do not work for me on android 4.4.2.
min sdk level 11, max 21.
What worked for me was the following:
this correctly catches the constraint, and you can do your handling inside the catch block.
RR.