]> git.ktnx.net Git - mobile-ledger.git/commitdiff
stop closing acuired db handles and leave that for the application termination
authorDamyan Ivanov <dam+mobileledger@ktnx.net>
Sat, 5 Jan 2019 07:58:34 +0000 (07:58 +0000)
committerDamyan Ivanov <dam+mobileledger@ktnx.net>
Sat, 5 Jan 2019 07:58:34 +0000 (07:58 +0000)
these aren't reference-counted and can be destroyed by one thread while
another still uses them

app/src/main/java/net/ktnx/mobileledger/MobileLedgerApplication.java
app/src/main/java/net/ktnx/mobileledger/async/RetrieveAccountsTask.java
app/src/main/java/net/ktnx/mobileledger/async/UpdateTransactionsTask.java
app/src/main/java/net/ktnx/mobileledger/ui/transaction_list/TransactionListAdapter.java
app/src/main/java/net/ktnx/mobileledger/utils/MLDB.java

index f4a7215992face74b717ee283979f970bcfdcd48..20762c07a9ee76b5c66db1d953ca8c5cf9f8f6eb 100644 (file)
@@ -34,6 +34,11 @@ public class MobileLedgerApplication extends Application {
         MLDB.init(this);
     }
     @Override
+    public void onTerminate() {
+        MLDB.done();
+        super.onTerminate();
+    }
+    @Override
     public void onConfigurationChanged(Configuration newConfig) {
         super.onConfigurationChanged(newConfig);
         updateColorValues();
index e046040e137b92431615455e20b9e89adaff7829..8602ed1430f48845410597bf387bee1ac295c176 100644 (file)
@@ -60,116 +60,113 @@ public class RetrieveAccountsTask extends android.os.AsyncTask<Void, Integer, Vo
         try {
             HttpURLConnection http = NetworkUtil.prepare_connection(pref, "add");
             publishProgress(0);
-            try (SQLiteDatabase db = MLDB.getWritableDatabase()) {
-                try (InputStream resp = http.getInputStream()) {
-                    Log.d("update_accounts", String.valueOf(http.getResponseCode()));
-                    if (http.getResponseCode() != 200) {
-                        throw new IOException(
-                                String.format("HTTP error: %d %s", http.getResponseCode(),
-                                        http.getResponseMessage()));
-                    }
-                    else {
-                        if (db.inTransaction()) throw new AssertionError();
-
-                        db.beginTransaction();
-
-                        try {
-                            db.execSQL("update account_values set keep=0;");
-                            db.execSQL("update accounts set keep=0;");
-
-                            String line;
-                            String last_account_name = null;
-                            BufferedReader buf =
-                                    new BufferedReader(new InputStreamReader(resp, "UTF-8"));
-                            // %3A is '='
-                            Pattern account_name_re =
-                                    Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
-                            Pattern account_value_re = Pattern.compile(
-                                    "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
-                            Pattern tr_end_re = Pattern.compile("</tr>");
-                            Pattern descriptions_line_re =
-                                    Pattern.compile("\\bdescriptionsSuggester\\s*=\\s*new\\b");
-                            Pattern description_items_re =
-                                    Pattern.compile("\"value\":\"([^\"]+)\"");
-                            int count = 0;
-                            while ((line = buf.readLine()) != null) {
-                                throwIfCancelled();
-
-                                Matcher m = account_name_re.matcher(line);
-                                if (m.find()) {
-                                    String acct_encoded = m.group(1);
-                                    String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
-                                    acct_name = acct_name.replace("\"", "");
-                                    Log.d("account-parser", acct_name);
-
-                                    addAccount(db, acct_name);
-                                    publishProgress(++count);
-
-                                    last_account_name = acct_name;
-
-                                    continue;
-                                }
+            SQLiteDatabase db = MLDB.getWritableDatabase();
+            try (InputStream resp = http.getInputStream()) {
+                Log.d("update_accounts", String.valueOf(http.getResponseCode()));
+                if (http.getResponseCode() != 200) {
+                    throw new IOException(String.format("HTTP error: %d %s", http.getResponseCode(),
+                            http.getResponseMessage()));
+                }
+                else {
+                    if (db.inTransaction()) throw new AssertionError();
+
+                    db.beginTransaction();
+
+                    try {
+                        db.execSQL("update account_values set keep=0;");
+                        db.execSQL("update accounts set keep=0;");
+
+                        String line;
+                        String last_account_name = null;
+                        BufferedReader buf =
+                                new BufferedReader(new InputStreamReader(resp, "UTF-8"));
+                        // %3A is '='
+                        Pattern account_name_re =
+                                Pattern.compile("/register\\?q=inacct%3A([a-zA-Z0-9%]+)\"");
+                        Pattern account_value_re = Pattern.compile(
+                                "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
+                        Pattern tr_end_re = Pattern.compile("</tr>");
+                        Pattern descriptions_line_re =
+                                Pattern.compile("\\bdescriptionsSuggester\\s*=\\s*new\\b");
+                        Pattern description_items_re = Pattern.compile("\"value\":\"([^\"]+)\"");
+                        int count = 0;
+                        while ((line = buf.readLine()) != null) {
+                            throwIfCancelled();
+
+                            Matcher m = account_name_re.matcher(line);
+                            if (m.find()) {
+                                String acct_encoded = m.group(1);
+                                String acct_name = URLDecoder.decode(acct_encoded, "UTF-8");
+                                acct_name = acct_name.replace("\"", "");
+                                Log.d("account-parser", acct_name);
+
+                                addAccount(db, acct_name);
+                                publishProgress(++count);
+
+                                last_account_name = acct_name;
+
+                                continue;
+                            }
 
-                                Matcher tr_m = tr_end_re.matcher(line);
-                                if (tr_m.find()) {
-                                    Log.d("account-parser", "<tr> - another account expected");
-                                    last_account_name = null;
-                                    continue;
-                                }
+                            Matcher tr_m = tr_end_re.matcher(line);
+                            if (tr_m.find()) {
+                                Log.d("account-parser", "<tr> - another account expected");
+                                last_account_name = null;
+                                continue;
+                            }
 
-                                if (last_account_name != null) {
-                                    m = account_value_re.matcher(line);
-                                    boolean match_found = false;
-                                    while (m.find()) {
-                                        throwIfCancelled();
-
-                                        match_found = true;
-                                        String value = m.group(1);
-                                        String currency = m.group(2);
-                                        if (currency == null) currency = "";
-                                        value = value.replace(',', '.');
-                                        Log.d("db", "curr=" + currency + ", value=" + value);
-                                        db.execSQL(
-                                                "insert or replace into account_values(account, currency, value, keep) values(?, ?, ?, 1);",
-                                                new Object[]{last_account_name, currency,
-                                                             Float.valueOf(value)
-                                                });
-                                    }
-
-                                    if (match_found) continue;
+                            if (last_account_name != null) {
+                                m = account_value_re.matcher(line);
+                                boolean match_found = false;
+                                while (m.find()) {
+                                    throwIfCancelled();
+
+                                    match_found = true;
+                                    String value = m.group(1);
+                                    String currency = m.group(2);
+                                    if (currency == null) currency = "";
+                                    value = value.replace(',', '.');
+                                    Log.d("db", "curr=" + currency + ", value=" + value);
+                                    db.execSQL(
+                                            "insert or replace into account_values(account, currency, value, keep) values(?, ?, ?, 1);",
+                                            new Object[]{last_account_name, currency,
+                                                         Float.valueOf(value)
+                                            });
                                 }
 
-                                m = descriptions_line_re.matcher(line);
-                                if (m.find()) {
-                                    db.execSQL("update description_history set keep=0;");
-                                    m = description_items_re.matcher(line);
-                                    while (m.find()) {
-                                        throwIfCancelled();
-
-                                        String description = m.group(1);
-                                        if (description.isEmpty()) continue;
-
-                                        Log.d("db", String.format("Stored description: %s",
-                                                description));
-                                        db.execSQL("insert or replace into description_history" +
-                                                   "(description, description_upper, keep) " +
-                                                   "values(?, ?, 1);",
-                                                new Object[]{description, description.toUpperCase()
-                                                });
-                                    }
-                                }
+                                if (match_found) continue;
                             }
 
-                            db.execSQL("delete from account_values where keep=0;");
-                            db.execSQL("delete from accounts where keep=0;");
-                            db.setTransactionSuccessful();
-                        }
-                        catch (OperationCanceledException e) {
-                            Log.w("async", "Account retrieval cancelled");
-                        }
-                        finally {
-                            db.endTransaction();
+                            m = descriptions_line_re.matcher(line);
+                            if (m.find()) {
+                                db.execSQL("update description_history set keep=0;");
+                                m = description_items_re.matcher(line);
+                                while (m.find()) {
+                                    throwIfCancelled();
+
+                                    String description = m.group(1);
+                                    if (description.isEmpty()) continue;
+
+                                    Log.d("db",
+                                            String.format("Stored description: %s", description));
+                                    db.execSQL("insert or replace into description_history" +
+                                               "(description, description_upper, keep) " +
+                                               "values(?, ?, 1);",
+                                            new Object[]{description, description.toUpperCase()
+                                            });
+                                }
+                            }
                         }
+
+                        db.execSQL("delete from account_values where keep=0;");
+                        db.execSQL("delete from accounts where keep=0;");
+                        db.setTransactionSuccessful();
+                    }
+                    catch (OperationCanceledException e) {
+                        Log.w("async", "Account retrieval cancelled");
+                    }
+                    finally {
+                        db.endTransaction();
                     }
                 }
             }
index 0509f3531cd887236c7c61778d692635ed4709f5..b3e2e0c519793173b87f3b60dcdb666948a02960 100644 (file)
@@ -52,16 +52,15 @@ public class UpdateTransactionsTask extends AsyncTask<String, Void, List<LedgerT
             }
 
             Log.d("tmp", sql);
-            try (SQLiteDatabase db = MLDB.getReadableDatabase()) {
-                try (Cursor cursor = db.rawQuery(sql, params)) {
-                    while (cursor.moveToNext()) {
-                        if (isCancelled()) return null;
+            SQLiteDatabase db = MLDB.getReadableDatabase();
+            try (Cursor cursor = db.rawQuery(sql, params)) {
+                while (cursor.moveToNext()) {
+                    if (isCancelled()) return null;
 
-                        newList.add(new LedgerTransaction(cursor.getInt(0)));
-                    }
-                    Data.transactions.set(newList);
-                    Log.d("transactions", "transaction value updated");
+                    newList.add(new LedgerTransaction(cursor.getInt(0)));
                 }
+                Data.transactions.set(newList);
+                Log.d("transactions", "transaction value updated");
             }
 
             return newList;
index 807c04f119b08729b9906eb36a9884f3f5194619..bcdc198216d8fa561a7f28aa8932ead2e52c8ab7 100644 (file)
@@ -84,19 +84,19 @@ public class TransactionListAdapter extends RecyclerView.Adapter<TransactionRowH
         protected Void doInBackground(TransactionLoaderParams... p) {
             LedgerTransaction tr = p[0].transaction;
 
-            try (SQLiteDatabase db = MLDB.getReadableDatabase()) {
-                tr.loadData(db);
+            SQLiteDatabase db = MLDB.getReadableDatabase();
+            tr.loadData(db);
 
-                publishProgress(new TransactionLoaderStep(p[0].holder, p[0].position, tr));
+            publishProgress(new TransactionLoaderStep(p[0].holder, p[0].position, tr));
 
-                int rowIndex = 0;
-                for (LedgerTransactionAccount acc : tr.getAccounts()) {
-                    publishProgress(new TransactionLoaderStep(p[0].holder, acc, rowIndex++,
-                            p[0].boldAccountName));
-                }
-
-                publishProgress(new TransactionLoaderStep(p[0].holder, p[0].position, rowIndex));
+            int rowIndex = 0;
+            for (LedgerTransactionAccount acc : tr.getAccounts()) {
+                publishProgress(new TransactionLoaderStep(p[0].holder, acc, rowIndex++,
+                        p[0].boldAccountName));
             }
+
+            publishProgress(new TransactionLoaderStep(p[0].holder, p[0].position, rowIndex));
+
             return null;
         }
         @Override
index 443e0a9a5bdc2eedffeb3e55472d798c2be8065d..e43040601c94ebde0afc22d65967903e6466ba26 100644 (file)
@@ -92,32 +92,30 @@ public final class MLDB {
     }
     static public String get_option_value(String name, String default_value) {
         Log.d("db", "about to fetch option " + name);
-        try (SQLiteDatabase db = getReadableDatabase()) {
-            try (Cursor cursor = db
-                    .rawQuery("select value from options where name=?", new String[]{name}))
-            {
-                if (cursor.moveToFirst()) {
-                    String result = cursor.getString(0);
+        SQLiteDatabase db = getReadableDatabase();
+        try (Cursor cursor = db
+                .rawQuery("select value from options where name=?", new String[]{name}))
+        {
+            if (cursor.moveToFirst()) {
+                String result = cursor.getString(0);
 
-                    if (result == null) result = default_value;
+                if (result == null) result = default_value;
 
-                    Log.d("db", "option " + name + "=" + result);
-                    return result;
-                }
-                else return default_value;
-            }
-            catch (Exception e) {
-                Log.d("db", "returning default value for " + name, e);
-                return default_value;
+                Log.d("db", "option " + name + "=" + result);
+                return result;
             }
+            else return default_value;
+        }
+        catch (Exception e) {
+            Log.d("db", "returning default value for " + name, e);
+            return default_value;
         }
     }
     static public void set_option_value(String name, String value) {
         Log.d("db", "setting option " + name + "=" + value);
-        try (SQLiteDatabase db = getWritableDatabase()) {
-            db.execSQL("insert or replace into options(name, value) values(?, ?);",
-                    new String[]{name, value});
-        }
+        SQLiteDatabase db = getWritableDatabase();
+        db.execSQL("insert or replace into options(name, value) values(?, ?);",
+                new String[]{name, value});
     }
     static public void set_option_value(String name, long value) {
         set_option_value(name, String.valueOf(value));
@@ -143,28 +141,25 @@ public final class MLDB {
                 String[] col_names = {FontsContract.Columns._ID, field};
                 MatrixCursor c = new MatrixCursor(col_names);
 
-                try (SQLiteDatabase db = MLDB.getReadableDatabase()) {
-
-                    try (Cursor matches = db.rawQuery(String.format(
-                            "SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
-                            "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
-                            "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end " +
-                            "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' " + "ORDER BY 2, 1;",
-                            field, field, field, field, table, field),
-                            new String[]{str, str, str, str}))
-                    {
-                        int i = 0;
-                        while (matches.moveToNext()) {
-                            String match = matches.getString(0);
-                            int order = matches.getInt(1);
-                            Log.d("autocompletion", String.format("match: %s |%d", match, order));
-                            c.newRow().add(i++).add(match);
-                        }
+                SQLiteDatabase db = MLDB.getReadableDatabase();
+
+                try (Cursor matches = db.rawQuery(String.format(
+                        "SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
+                        "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
+                        "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end " + "FROM %s " +
+                        "WHERE %s_upper LIKE '%%'||?||'%%' " + "ORDER BY 2, 1;", field, field,
+                        field, field, table, field), new String[]{str, str, str, str}))
+                {
+                    int i = 0;
+                    while (matches.moveToNext()) {
+                        String match = matches.getString(0);
+                        int order = matches.getInt(1);
+                        Log.d("autocompletion", String.format("match: %s |%d", match, order));
+                        c.newRow().add(i++).add(match);
                     }
-
-                    return c;
                 }
 
+                return c;
             }
         };
 
@@ -175,6 +170,13 @@ public final class MLDB {
     public static void init(Context context) {
         MLDB.context = context.getApplicationContext();
     }
+    public static void done() {
+        if (helperForReading != null)
+            helperForReading.close();
+
+        if ((helperForWriting != helperForReading) && (helperForWriting != null))
+            helperForWriting.close();
+    }
     public enum DatabaseMode {READ, WRITE}
 }