Here's a short example of using transactions in SQLite (db is a SQLiteDatabase instance in the following):
try {
db.beginTransaction();
// your sql stuff
db.setTransactionSuccessful();
} catch(SQLException e) {
// do some error handling
} finally {
db.endTransaction();
}
Notice, its important that whatever method you choose to replace "//your sql stuff" with throws and exception. Use insertOrThrow
() or if you need more flexibility SQLiteStatement instances (their .execute methods always throws exceptions on error).
Notice, you do not need to explicititly rollback. If you call db.endTransaction()
without .setTransactionSuccessful()
it will roll back automatically.
Just remember always to put setTransactionSuccessful after your last SQLException throwing methods :)
You could easy extend this with another catch block, to catch exceptions for network time outs.
Now you can do is a cancel or a back button can act like a exception in this example and automatically the endTransaction will be called which will result in rollBack of your data