Android, handle SQLiteConstraintException

butelo picture butelo · Nov 7, 2011 · Viewed 8.4k times · Source

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.

Answer

Chris picture Chris · Nov 7, 2011

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