]> git.ktnx.net Git - mobile-ledger.git/blobdiff - app/src/main/java/net/ktnx/mobileledger/async/RetrieveAccountsTask.java
remove context parameter from MLDB.getWritableDB
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / async / RetrieveAccountsTask.java
index 3d96d3270f188bb09346769a63ac3325b0e147f9..83f15fb7e7dec9258a7e35cef6829c2d4bca9167 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright © 2018 Damyan Ivanov.
+ * Copyright © 2019 Damyan Ivanov.
  * This file is part of Mobile-Ledger.
  * Mobile-Ledger is free software: you can distribute it and/or modify it
  * under the term of the GNU General Public License as published by
@@ -21,9 +21,9 @@ import android.content.SharedPreferences;
 import android.database.sqlite.SQLiteDatabase;
 import android.util.Log;
 
-import net.ktnx.mobileledger.AccountSummary;
 import net.ktnx.mobileledger.R;
 import net.ktnx.mobileledger.model.LedgerAccount;
+import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
 import net.ktnx.mobileledger.utils.MLDB;
 import net.ktnx.mobileledger.utils.NetworkUtil;
 
@@ -41,11 +41,10 @@ import java.util.regex.Pattern;
 
 public class RetrieveAccountsTask extends android.os.AsyncTask<Void, Integer, Void> {
     int error;
-
+    WeakReference<AccountSummaryFragment> mContext;
     private SharedPreferences pref;
-    WeakReference<AccountSummary> mContext;
 
-    public RetrieveAccountsTask(WeakReference<AccountSummary> context) {
+    public RetrieveAccountsTask(WeakReference<AccountSummaryFragment> context) {
         mContext = context;
         error = 0;
     }
@@ -56,110 +55,116 @@ public class RetrieveAccountsTask extends android.os.AsyncTask<Void, Integer, Vo
 
     protected Void doInBackground(Void... params) {
         try {
-            HttpURLConnection http = NetworkUtil.prepare_connection( pref, "add");
+            HttpURLConnection http = NetworkUtil.prepare_connection(pref, "add");
             publishProgress(0);
-            try (SQLiteDatabase db = MLDB.getDatabase(mContext.get(), MLDB.DatabaseMode.WRITE)) {
-                    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 value_re = Pattern.compile(
-                                        "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
-                                Pattern tr_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) {
-                                    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;
-                                    }
+            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 value_re = Pattern.compile(
+                                    "<span class=\"[^\"]*\\bamount\\b[^\"]*\">\\s*([-+]?[\\d.,]+)(?:\\s+(\\S+))?</span>");
+                            Pattern tr_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) {
+                                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_re.matcher(line);
-                                    if (tr_m.find()) {
-                                        Log.d("account-parser", "<tr> - another account expected");
-                                        last_account_name = null;
-                                        continue;
-                                    }
+                                Matcher tr_m = tr_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 = value_re.matcher(line);
-                                        boolean match_found = false;
-                                        while (m.find()) {
-                                            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 = value_re.matcher(line);
+                                    boolean match_found = false;
+                                    while (m.find()) {
+                                        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()) {
-                                            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.execSQL("delete from description_history where keep=0;");
-                                db.setTransactionSuccessful();
-                            }
-                            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()) {
+                                        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.execSQL("delete from description_history where keep=0;");
+                            db.setTransactionSuccessful();
+                        }
+                        finally {
+                            db.endTransaction();
                         }
+
                     }
                 }
             }
-        } catch (MalformedURLException e) {
+        }
+        catch (MalformedURLException e) {
             error = R.string.err_bad_backend_url;
             e.printStackTrace();
         }
@@ -182,18 +187,17 @@ public class RetrieveAccountsTask extends android.os.AsyncTask<Void, Integer, Vo
     private void addAccount(SQLiteDatabase db, String name) {
         do {
             LedgerAccount acc = new LedgerAccount(name);
-            db.execSQL(
-                    "update accounts set level = ?, keep = 1 where name = ?",
+            db.execSQL("update accounts set level = ?, keep = 1 where name = ?",
                     new Object[]{acc.getLevel(), name});
-            db.execSQL("insert into accounts(name, name_upper, parent_name, level) select ?,?,"
-                            + "?,? " + "where (select changes() = 0)",
+            db.execSQL("insert into accounts(name, name_upper, parent_name, level) select ?,?," +
+                       "?,? " + "where (select changes() = 0)",
                     new Object[]{name, name.toUpperCase(), acc.getParentName(), acc.getLevel()});
             name = acc.getParentName();
         } while (name != null);
     }
     @Override
     protected void onPostExecute(Void result) {
-        AccountSummary ctx = mContext.get();
+        AccountSummaryFragment ctx = mContext.get();
         if (ctx == null) return;
         ctx.onAccountRefreshDone(this.error);
     }