beginTransaction and endTransaction exception handling

3

I execute an insert without any problem but when I run another insert I should mark error because inside that table there is a primary key and then the error remains but in the android monitor although I do the log.e (blah blah blah); it is as if the exception were thrown.

public long insertarTipo(List<Tipo> tipo) {
        long n = 1;
        this.openWriteableDB();
        db.beginTransaction();
        try {
            if (tipo.size() > 0) {
                ContentValues tt = new ContentValues();

                    n = db.insert("Tipo", null, tt);
                }
            }
            db.setTransactionSuccessful();
        } catch (Exception e) {
            Log.e(Errors.ERROR_TAG, e.getMessage(), e);
        } finally {
            db.endTransaction();
        }
        return n;
    }
asked by Jorge Luis Pilo Torres 23.08.2016 в 23:40
source

1 answer

1

Firstly I commented on the method insert () , if an error is occurring when performing this operation, it does not cause an error.

The documentation indicates:

  

insert () : Returns the id of the new row inserted or -1 if an error has occurred   happened.

What you have to do is validate this way:

long n = db.insert("Tipo", null, tt);
if(n == -1){
   //Ocurrio un error! =(.
}else{
   //Inserción exitosa!
}

Regarding your other problem: "Primary Key must be unique".

This error occurs when you try to insert a record with a primary key (Primary Key) that already exists! Check which is the field that is defined as Primary Key, I think maybe it is "Id", ensure that a value that already exists is not inserted:

 tt.put("Id", tipo.getIdTipo());
    
answered by 23.08.2016 в 23:47