Database transactions

SDK Version: 

In android it is highly important to use transactions when working with databases.

First, in android database operations - especially writing - are very slow. Batching them into transactions will make them much faster.

Second, the database remains consistent under any circumstances. The database system makes sure to all the operations in a transaction take effect, or on error, rollback all of them.

If you are used to other platforms like PHP+MySQL where the code usually runs on a powerful server, witch is not likely to stop execution "unexpectedly", you can be surprised how much it affects the performance in android.
The android system can kill apps/threads/activities and so interrupt database usage, the battery can discharge or can be removed etc.

The implementation is very simple, using 3 methods in the SQLiteDatabase class:


When calling endTransaction() all operations done since beginTransaction() are committed if endTransaction() have been called, or are rolled back otherwise.

An example how the main flow of a database method can look:

  1. mDatabase.beginTransaction();
  2. try{
  3.   //do multiple database operations here
  4.   //which throws exceptions on error
  5.   mDatabase.setTransactionSuccessful();
  6.   //do not any more database operations between
  7.   //setTransactionSuccessful and endTransaction
  8.   }catch(Exception e){
  9.     //end the transaction on error too when doing exception handling
  10.     mDatabase.endTransaction();
  11.     throw e;
  12.   }
  13.   //end the transaction on no error
  14.   mDatabase.endTransaction();
  15. }