Why we need transactions, when we work with database in Android?

Picture from freepic.com

As we can see in one of difinitions:

Transaction (the transaction English, from Latin transactio -.. Agreement, contract) — the lowest logically meaningful operation that makes sense and can be effected only in full.

Based on this definition, it follows that when referring to anything in a transaction when an error occurs, the data loss is excluded.

Many of us know or imagine, what is a transaction in the event of a transfer of money. What problems can arise without a transaction?

You pay for the purchase of a new TV via the Internet bank. There are no transactions. You fill the data fields, press the send button. At this point, your money is withdrawn from your account and go in the direction of an online store. But an unfortunate accident, because of some errors, do not reach the seller. Your money have gone into “nowhere”. You can’t demand your money back. There is nobody to demand.

For such cases, it was invented protection — transaction.

In Android, when working with a database, is also recommended to use transactions when manipulating data.

There are three main actions that we need to do during transactions in Android:

  1. Begin transaction -database.beginTransaction()-

2. Upon successful completion, indicate that the transaction is successful -database.setTransactionSuccessful()- and to complete the transaction -database.endTransaction()-

3. When incorrect event in the transaction (error) to complete the transaction -database.endTransaction()-

It remains an open question: “How exactly to handle errors?”. The answer is simple — using the try-catch-finally.

Here is a small snippet of code, for example:

{
SomeDbHelper dbHelper = new SomeDbHelper(context);
SQLiteDatabase database = dbHelper.getWritableDatabase();

database.beginTransaction();

try {
ContentValues someContentValues = new ContentValues();
someContentValues.put("name", someNameString);

database.insert("Table", null, someContentValues);

database.setTransactionSuccessful();
database.endTransaction();

dbHelper.close();
}
catch (SQLiteException exception)
{
exception.printStackTrace();

database.endTransaction();
dbHelper.close();}
}

In this case, I repeat, with the successful insertion of data, transaction is successful, and the data in the database. On error, the transaction is completed and the data will not in the database.

Hope it helps.

Kind regards.

Author’s blog: http://junior-freelancer.weebly.com/