Android, handle SQLiteConstraintException Android, handle SQLiteConstraintException sqlite sqlite

Android, handle SQLiteConstraintException


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


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)


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 instanceString 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_COLUMNIS THE UNIQUE COLUMN DEFINED WHILE CREATING THE TABLE.*/database == //get a writable database instancetry{                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.