DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Data Engineering
  3. Databases
  4. Design Pattern: Database Transaction Handling (in Android)

Design Pattern: Database Transaction Handling (in Android)

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

Sagar Garg user avatar by
Sagar Garg
·
Sep. 19, 18 · Tutorial
Like (2)
Save
Tweet
Share
9.53K Views

Join the DZone community and get the full member experience.

Join For Free

This article is about database transaction handling and its design pattern in android. It also gives a brief explanation 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 has its two child methods, and 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 the database instance
  • Start the database transaction
  • Mark the transaction as successful
  • Commit or rollback the transaction
  • Close the database
public static void prepareData() throws <Name of the app>AppException
{
    try
    {
        //Get Database Instance
        sqliteDatabase = DBUtils.openWritableDatabase();

        //Start Database Transaction
        DBUtils.beginTransaction(sqliteDatabase);

        prepareData1(sqLiteDatabase);
        prepareData2(sqLiteDatabase);

        //Mark Transaction Successful
        setTransactionSuccessful(sqLiteDatabase);
    }
    catch (Exception exception)
    {
        String exceptionMessage = "Error in inserting data."
        ExceptionManager.processException(AppConstant.ERROR_CODE_1015,
                exceptionMessage, exception);
    }
    finally
    {
        //Commit or Rollback transaction
        endTransaction(sqLiteDatabase);
        //Close Database
        appDatabase.closeDatabase();
    }
}

1.1 Get Database Instance

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

In DbUtil class create openWritableDatabase()
/**
 * Opens the database
 * @return
 */
public static SQLiteDatabase openWritableDatabase()
{
    SQLiteDatabase sqliteDatabase = null;

    // Opening new database
    sqliteDatabase = sqliteOpenHelper.getWritableDatabase();

    //Enable Write Ahead Logging
    sqliteDatabase.enableWriteAheadLogging();

    return sqliteDatabase;
}

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

In DbUtil class create openReadableDatabase()
/**
 * Opens the database
 * @return
 */
public static SQLiteDatabase openReadableDatabase()
{
    SQLiteDatabase sqliteDatabase = null;

    // Opening new database
    sqliteDatabase = sqliteOpenHelper.getReadableDatabase();

    return sqliteDatabase;
}

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.

In DbUtils class create beginTransaction() method:
public static void beginTransaction(SQLiteDatabase sqLiteDatabase)
{
    try
    {
        if(sqLiteDatabase != null)
        {
            sqLiteDatabase.beginTransaction();
        }
    }
    catch(Exception exception)
    {
        //Consume Exception
    }
}

1.3 Mark Transaction Successful

setTransactionSuccessful(SQLiteDatabase sqLiteDatabase) method is used to mark our transaction successful. All database related tasks 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.

In DbUtils class createsetTransactionSuccessful(SQLiteDatabase sqliteDatabase) :
public static void setTransactionSuccessful(SQLiteDatabase sqLiteDatabase)
{
    try
    {
        if(sqLiteDatabase != null)
        {
            sqLiteDatabase.setTransactionSuccessful();
        }
    }
    catch(Exception exception)
    {
        //Consume Exception
    }
}

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 as successful by setTransactionSuccessful() method, then our transaction will be committed, else all changes will be rollback.

In DbUtils class create endTransaction(SQLiteDatabase sqLiteDatabase) method :
public static void endTransaction(SQLiteDatabase sqLiteDatabase)
{
    try
    {
        if(sqLiteDatabase != null)
        {
            sqLiteDatabase.endTransaction();
        }
    }
    catch(Exception exception)
    {
        //Consume Exception
    }
}

1.4 Close Database

   //Close Database
   appDatabase.closeDatabase();

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
private static void prepareData1(SQLiteDatabase sqLiteDatabase)
        throws <Name of the app>AppException
{
    ContentValues contentValues = null;
    long rowId = 0;

    try
    {
        //Prepare ContentValues object
        contentValues = new ContentValues();

        //Execute Query
        rowId = sqLiteDatabase.insertOrThrow("Table Name", null, contentValues);

        //If rowId is -1 then this means that Row was not inserted.
        //Something went wrong. Throw Exception
        if (rowId == -1)
        {
            String exceptionMessage = "Error in inserting Data. Row Id is -1.";
            throw new <Name of the App>AppException
                (AppConstant.ERROR_CODE_1011, exceptionMessage);
        }
    }
    catch (Exception exception)
    {
         //Handle Exception
        String exceptionMessage = "Error in inserting Data.";
        int errorCode = AppConstant.ERROR_CODE_8012;
        ExceptionManager.dispatchExceptionDetails(errorCode, message, 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.

//Execute Query
rowId = sqLiteDatabase.insertOrThrow("Table Name", null, contentValues);

//If rowId is -1 then this means that Row was not inserted.
//Something went wrong. Throw Exception
if (rowId == -1)
{
   String exceptionMessage = "Error in inserting Data. Row Id is -1.";
   throw new <Name of the App>AppException
      (AppConstant.ERROR_CODE_1011, exceptionMessage);
}

2.2 Handle Exception

catch (Exception exception)
{
   //Handle Exception
   String exceptionMessage = "Error in inserting Data.";
   int errorCode = AppConstant.ERROR_CODE_8012;
   ExceptionManager.dispatchExceptionDetails(errorCode, message, exception);
}

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

public static void dispatchExceptionDetails(int exceptionCode, String exceptionMessage, Exception exceptionObject) throws <Name of the App>AppException
{
   if(exceptionObject instanceof AppException)
   {
      throw (AppException) exceptionObject;
   }
   else
   {
      //Log Exception details
      logException(exceptionCode, exceptionMessage, exceptionObject);

      //Throw Exception
      throw new <Name of the App>AppException(exceptionCode, exceptionMessage);
   }
}

3. Another Method Joins the Database Transaction

private static void prepareData2(SQLiteDatabase sqLiteDatabase)
      throws <Name of the app>AppException
{
   ContentValues contentValues = null;
   long rowId = 0;

   try
   {
      contentValues = new ContentValues();
      //Prepare ContentValues object

      rowId = sqLiteDatabase.insertOrThrow("Table Name", null, contentValues);

      //If rowId is -1 then this means that Row was not inserted.
           //Something went wrong. Throw Exception
      if (rowId == -1)
      {
         String exceptionMessage = "Error in inserting Data. Row Id is -1.";
         throw new <Name of the App>AppException
            (AppConstant.ERROR_CODE_1013, exceptionMessage);
      }
   }
   catch (Exception exception)
   {
      //Handle Exception
      String exceptionMessage = "Error in inserting Data.";
      int errorCode = AppConstant.ERROR_CODE_8012;
      ExceptionManager.dispatchExceptionDetails(errorCode, message, exception);
   }
}
Database Database transaction Android (robot) Design

Published at DZone with permission of Sagar Garg. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Strategies for Kubernetes Cluster Administrators: Understanding Pod Scheduling
  • Microservices Testing
  • Asynchronous Messaging Service
  • AWS CodeCommit and GitKraken Basics: Essential Skills for Every Developer

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: