问题
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.
回答1:
Try using insertOrThrow. Otherwise, insert just returns -1 in the event of an error.
回答2:
When you execute to add the values in the database from the entry class add boolean to control the data ex:
boolean DBAccepted = DBhelper.addData(blabla);
if(DBAccepted ==false)
{
Toast.maketext (this,"There is a conflict",Toast.LengthLong ).show();
}
in the DBhelper Class :
public boolean addData(String blablabla){
DBAccepted =true;
ContentValues cv = new ContentValues();
cv.put(key_value, blablabla);
Databes.insertOrThrow(TABLE_SCORES, null, cv);
} catch (SQLiteConstraintException e) {
// TODO Auto-generated catch block
System.out.println(e);
DBAccepted =false;
}
return DBAccepted ;
}
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)
回答3:
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:
/*FIRST INSERT A VALUE*/
database = //get a writable database instance
String MESSAGES_TABLE = "messages";
ContentValues cv= new ContentValues();
cv.put("unique_id_column","unique_id");
database.insert(MESSAGES_TABLE,null,cv);
database.close();
/*NOW LETS TRY TO INSERT ANOTHER RECORD, WITH THE SAME VALUE, WHERE UNIQUE_ID_COLUMN
IS THE UNIQUE COLUMN DEFINED WHILE CREATING THE TABLE.*/
database == //get a writable database instance
try{
long new_row_id = database.insertWithOnConflict(MESSAGES_TABLE, null,cv,SQLiteDatabase.CONFLICT_FAIL);
Log.d(SS_DATABASE_TAG,"the new row id is ---> " + String.valueOf(new_row_id));
}
catch(SQLiteConstraintException e)
{
Log.d(SS_DATABASE_TAG,"caught the contraint.");
}
database.close();
this correctly catches the constraint, and you can do your handling inside the catch block.
RR.
来源:https://stackoverflow.com/questions/8040415/android-handle-sqliteconstraintexception