Search code examples
androidsqliteexceptionhandleconstraints

Android, handle SQLiteConstraintException


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.


Solution

  • Try using insertOrThrow. Otherwise, insert just returns -1 in the event of an error.