2
\$\begingroup\$

I got tired of following Android-SQLite's transaction idiom, briefly documented here.

It requires too much boilerplate code, IMHO, especially when you add the obligatory null checks. So I came up with this pattern, inspired by the Objective-C library FMDB:

// Inside the class that manages the database
interface Transaction {
    // return false to rollback
    boolean execute(SQLiteDatabase db);
}

boolean doTransaction(Transaction transaction) {
    boolean success = false;
    SQLiteDatabase db = null;
    try {
        db = mHelper.getWritableDatabase();

        if (db != null) {
            db.beginTransaction();

            success = transaction.execute(db);

            if (success) {
                db.setTransactionSuccessful();
            }
        }
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }
    return success;
}

Usage:

// In a method in that same database-managing class
doTransaction(new Transaction() {
    @Override
    public boolean run(SQLiteDatabase db) {
         // ... write to db ...
         return true; // or false to rollback
    }
});

Of course, both the Transaction interface and the doTransaction() method can be made available to other classes.

Does this look like a good idea? There are probably complex transactions that can't use it, but so far all of my transactions fit.

Am I missing something important with this pattern, like forgetting to close something, handle exceptions, etc? Or maybe it's just not "The Java Way" or "The Android Way" of doing things?

\$\endgroup\$
  • \$\begingroup\$ This looks pretty neat! Sounds like a very good idea and I would use it. As nitpick about naming, I would call the interface method execute instead of run. \$\endgroup\$ – janos May 28 '15 at 20:47
  • \$\begingroup\$ Have you considered using an ORM? Eg. ActiveAndroid, DBFlow,..? If you prefer to write your own queries I would rather go for a generic implementation rather than a callback to differentiate between transactions. \$\endgroup\$ – user1281750 Jun 2 '15 at 11:45
  • \$\begingroup\$ @user1281750 I'll consider the ORM option, thank you. \$\endgroup\$ – noamtm Jun 2 '15 at 11:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.