Design Pattern – Database Transaction Handling (in Android)

This blog is about database transaction handling and its design pattern in android. It also gives a brief knowledge on how to handle Exception.

Here we have a main method which is responsible to get  database instance  -> start Database Transaction  ->  Mark Transaction Successful   ->  Commit or Rollback Transaction  ->  Close database. This main method have its two child method both methods perform some database transaction

1 . Main method defines Transaction boundaries.

2.  Methods joins the Database transaction.

3.  Another Method joins the Database Transaction.

1 . Main method defines Transaction boundaries :

This method will:

  • Get Database instance.
  • Start Database Transaction.
  • Mark Transaction Successful.
  • Commit or Rollback Transaction.
  • Close Database.

1.1 Get Database Instance

  • DbUtils.openWritableDatabase()  –  If our requirement is to fetch the data from database ,                                                       we have to use openWritableDatabase() method.

  • DbUtils.openReadableDatabase() – If our requirement is to read the data from database                                                                      use  openReadableDatabase() method.

1.2  Start Database Transaction
  • beginTransaction(SQLiteDatabase sqLiteDatabase)  – This method is used to begin our            transaction in EXCLUSIVE mode and when parent transaction is completed all child        transactions will be rollback or commit ed.

1.3  Mark Transaction Successful:
  • setTransactionSuccessful(SQLiteDatabase sqLiteDatabase) method is used to mark our transaction successful. All database related task must be only done between beginTransaction() method and setTransactionSuccessful(SQLiteDatabase sqliteDatabase)  method.Do not do any database related task between setTransactionSuccessful(SQLiteDatabase sqliteDatabase) method and endTransaction(SQLiteDatabase sqLiteDatabase) method.

1.4  Commit or Rollback Transaction

  • endTransaction(SQLiteDatabase sqLiteDatabase)  – This method is used to commit or rollback our database transaction.If our transaction is marked successful by setTransactionSuccessful() method then our transaction will be commited else all changes will be rollback.

1.4  Close Database.

2 . Method joins the Database Transaction

This is the child transaction of prepareData() method here  SQLiteDatabase object must be passed from parent transaction method .

  1. Exceute query.
  2. Handle Exception

2.1 Execute Query

Here we are inserting data in database and after execution of query we have to check whether our data is inserted or not. If our data is not inserted thow AppException.

2.2 Handle Exception

ExceptionManager.dispatchExceptionDetails(errorCode, message, exception) method is used to throw  or create AppException object.

3 . Another Method joins the Database Transaction

 

 

Leave a Reply