How to capture exceptions released by the Insert() method?

Asked

Viewed 99 times

1

I am using Sqlite for a local bank in an Android application, my problem is that I am unable to handle the integrity restriction exceptions. I have a table where the two fields are PK, that is, there can never be equal records. When I try to enter two equal data it throws the exception:

E/SQLiteDatabase: Error inserting DIA=08-03-2018 HORA=02:06
android.database.sqlite.SQLiteConstraintException: 
UNIQUE constraint failed: TBPONTOSTEMP.DIA, TBPONTOSTEMP.HORA (code 1555)

I need to treat this exception to give a message to the user, I have already used both Exception, as well as Sqliteexception, Sqliteconstraintexception. Follows the code:

public int cadastrarPontosTemp(String ponto, String dia){
    ContentValues values = new ContentValues();
    try{
        values.put("DIA",dia);
        values.put("HORA",ponto);
        getWritableDatabase().insert("TBPONTOSTEMP",null,values);
        Log.e("cadastrarPontosTemp","SUCESSO");

    }catch (SQLiteConstraintException e){
        Log.e("cadastrarPontosTemp",e.getMessage());
        return 1;
    }
    return 0;
}

1 answer

2


The method Insert() captures any launched Sqlexception, making your block try/catch useless with regard to Sqlexception type exceptions.

Source code of the method insert():

public long insert(String table, String nullColumnHack, ContentValues values) {

    try {

        return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);

    } catch (SQLException e) {

        Log.e(TAG, "Error inserting " + values, e);
        return -1;
    }
}

However, you can use the returned value to verify the successful insertion. The returned value will be the id of the new record or -1 in case of failure.

If you want an exception to be made use the method insertOrThrow().

Source code of the method insertOrThrow().

public long insertOrThrow(String table, String nullColumnHack, ContentValues values) throws SQLException {

    return insertWithOnConflict(table, nullColumnHack, values, CONFLICT_NONE);

}

Both call the method insertWithOnConflict() to do the Insert, passing the value CONFLICT_NONE to the parameter conflictAlgorithm.

The value passed to this parameter serves to indicate which "conflict algorithm" to use (see ON CONFLICT).
CONFLICT_NONE indicates that the "conflict algorithm" indicated in the table creation or the pattern that is ABORT.

Use this method when intending to use a different "conflict algorithm".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.