Actually you are doing wrong.
You have to set begin transaction if you have multiple records to insert into database or
if you have to rollback data from other table if there is a problem in inserting data in one of the database table.
For example
You have two tables
- A
- B
Now you want to insert data in these two tables but you will have to rollback transaction if you will get any error at the time of inserting data in the tables.
Now you have successfully insert data in table A and now you are trying to insert data in the table B.Now if you get error at the time of inserting data in the table B then you have to delete relevant data from table A that means you have to rollback the transaction.
How you can use database transaction in Android
- If you want to start the transaction there is a method
beginTransaction()
- If you want to commit the transaction there is a method
setTransactionSuccessful()
which will commit the values in the database - If you had start the transaction you need to close the transaction so there is a method
endTransaction()
which will end your database transaction
Now there are two main points
- If you want to set transaction successful you need to write
setTransactionSuccessful()
and thenendTransaction()
afterbeginTransaction()
- If you want to rollback your transaction then you need to
endTransaction()
without committing the transaction bysetTransactionSuccessful()
.
You can get detailed information about the SQLite database transaction from here
In your case
You can call your saveCustomer()
function in try and catch blocks
db.beginTransaction();
try {
saveCustomer();
db.setTransactionSuccessful();
} catch {
//Error in between database transaction
} finally {
db.endTransaction();
}