How to catch exceptions thrown by the insert () method?

2

I am using SQLite for a local bank in an Android application, my problem is that I am not able to handle health 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 handle this exception to give a message to the user, I have already used both the Exception and the SQLiteException, SQLiteConstraintException. Here is 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;
}
    
asked by anonymous 07.03.2018 / 03:38

1 answer

3

The method insert () captures any released SQLException, making its block try/catch useless with regard to exceptions of type SQLException.

Source Code of 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;
    }
}

You can however use the value returned to verify the success of the insert. The value returned will be the Id of the new record or -1 on failure.

If you want an exception to be thrown, use the insertOrThrow () .

Source Code of the insertOrThrow() method.

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

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

}

Both call the # to make the insert , passing the value CONFLICT_NONE to the parameter conflictAlgorithm .

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

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

    
07.03.2018 / 12:39