From aa7f9929801f4d7bf478d020d150c7ca9a4573ca Mon Sep 17 00:00:00 2001 From: Sam Bosley Date: Fri, 8 Feb 2013 16:01:40 -0800 Subject: [PATCH] Hopefully fixed a deadlock that could occur during database transactions (see http://stackoverflow.com/questions/11535222/recommended-design-pattern-for-writing-to-sqlite-database-in-android) --- .../com/todoroo/andlib/data/DatabaseDao.java | 52 ++++++++++--------- 1 file changed, 27 insertions(+), 25 deletions(-) diff --git a/api/src/com/todoroo/andlib/data/DatabaseDao.java b/api/src/com/todoroo/andlib/data/DatabaseDao.java index 17c4b27b4..afb021941 100644 --- a/api/src/com/todoroo/andlib/data/DatabaseDao.java +++ b/api/src/com/todoroo/andlib/data/DatabaseDao.java @@ -297,33 +297,35 @@ public class DatabaseDao { boolean recordOutstanding = shouldRecordOutstanding(item); final AtomicBoolean result = new AtomicBoolean(false); - if (recordOutstanding) { // begin transaction - database.getDatabase().beginTransactionWithListener(new SQLiteTransactionListener() { - @Override - public void onRollback() { - Log.e(ERROR_TAG, "Error inserting or updating rows", new Throwable()); //$NON-NLS-1$ - result.set(false); + synchronized(database) { + if (recordOutstanding) { // begin transaction + database.getDatabase().beginTransactionWithListener(new SQLiteTransactionListener() { + @Override + public void onRollback() { + Log.e(ERROR_TAG, "Error inserting or updating rows", new Throwable()); //$NON-NLS-1$ + result.set(false); + } + @Override + public void onCommit() {/**/} + @Override + public void onBegin() {/**/} + }); + } + int numOutstanding = 0; + try { + result.set(op.makeChange()); + if(result.get()) { + if (recordOutstanding && ((numOutstanding = createOutstandingEntries(item.getId(), values)) != -1)) // Create entries for setValues in outstanding table + database.getDatabase().setTransactionSuccessful(); } - @Override - public void onCommit() {/**/} - @Override - public void onBegin() {/**/} - }); - } - int numOutstanding = 0; - try { - result.set(op.makeChange()); - if(result.get()) { - if (recordOutstanding && ((numOutstanding = createOutstandingEntries(item.getId(), values)) != -1)) // Create entries for setValues in outstanding table - database.getDatabase().setTransactionSuccessful(); + } finally { + if (recordOutstanding) // commit transaction + database.getDatabase().endTransaction(); + } + if (result.get()) { + onModelUpdated(item, recordOutstanding && numOutstanding > 0); + item.markSaved(); } - } finally { - if (recordOutstanding) // commit transaction - database.getDatabase().endTransaction(); - } - if (result.get()) { - onModelUpdated(item, recordOutstanding && numOutstanding > 0); - item.markSaved(); } return result.get(); }