]> git.ktnx.net Git - mobile-ledger.git/blobdiff - app/src/main/java/net/ktnx/mobileledger/AccountSummary.java
migrate to a proper db helper class, sub-classed from SQLiteOpenHelper
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / AccountSummary.java
index 12436d5cc39c0af11f4d5a5f3d3188971b07f5d1..829b00b1717bb7f7e72bf4230e59c7b3b0528561 100644 (file)
@@ -2,9 +2,12 @@ package net.ktnx.mobileledger;
 
 import android.annotation.SuppressLint;
 import android.content.Intent;
+import android.content.SharedPreferences;
 import android.content.pm.PackageInfo;
 import android.content.res.Resources;
 import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
+import android.graphics.Typeface;
 import android.os.Build;
 import android.os.Bundle;
 import android.preference.PreferenceManager;
@@ -16,6 +19,7 @@ import android.support.v7.app.AppCompatActivity;
 import android.support.v7.widget.Toolbar;
 import android.util.Log;
 import android.util.TypedValue;
+import android.view.ContextMenu;
 import android.view.Gravity;
 import android.view.Menu;
 import android.view.MenuItem;
@@ -24,21 +28,24 @@ import android.view.ViewGroup;
 import android.widget.EditText;
 import android.widget.LinearLayout;
 import android.widget.ProgressBar;
-import android.widget.TableLayout;
-import android.widget.TableRow;
 import android.widget.TextView;
 
 import java.util.Date;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 import static android.view.View.GONE;
-import static net.ktnx.mobileledger.MobileLedgerDB.db;
-import static net.ktnx.mobileledger.MobileLedgerDB.set_option_value;
 
 public class AccountSummary extends AppCompatActivity {
     DrawerLayout drawer;
 
     private static long account_list_last_updated;
     private static boolean account_list_needs_update = true;
+    MenuItem mShowHiddenAccounts;
+    SharedPreferences.OnSharedPreferenceChangeListener sBindPreferenceSummaryToValueListener;
+    private AccountRowLayout clickedAccountRow;
+    private MobileLedgerDatabase dbh;
+
     public static void preferences_changed() {
         account_list_needs_update = true;
     }
@@ -51,6 +58,8 @@ public class AccountSummary extends AppCompatActivity {
         Toolbar toolbar = findViewById(R.id.toolbar);
         setSupportActionBar(toolbar);
 
+        dbh = new MobileLedgerDatabase(this);
+
         drawer = findViewById(R.id.drawer_layout);
         ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                 this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
@@ -71,9 +80,34 @@ public class AccountSummary extends AppCompatActivity {
         update_accounts(false);
     }
 
+    @Override
+    protected void onStart() {
+        super.onStart();
+        LinearLayout grp = drawer.findViewById(R.id.nav_actions);
+        for (int i = 0; i < grp.getChildCount(); i++) {
+            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+                grp.getChildAt(i).setBackgroundColor(
+                        getResources().getColor(R.color.drawer_background, getTheme()));
+            }
+            else {
+                grp.getChildAt(i)
+                        .setBackgroundColor(getResources().getColor(R.color.drawer_background));
+            }
+        }
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+            drawer.findViewById(R.id.nav_account_summary).setBackgroundColor(
+                    getResources().getColor(R.color.table_row_even_bg, getTheme()));
+        }
+        else {
+            drawer.findViewById(R.id.nav_account_summary)
+                    .setBackgroundColor(getResources().getColor(R.color.table_row_even_bg));
+        }
+    }
+
     public void fab_new_transaction_clicked(View view) {
         Intent intent = new Intent(this, NewTransactionActivity.class);
         startActivity(intent);
+        overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
     }
 
     public void nav_exit_clicked(View view) {
@@ -101,7 +135,25 @@ public class AccountSummary extends AppCompatActivity {
         // Inflate the menu; this adds items to the action bar if it is present.
         getMenuInflater().inflate(R.menu.account_summary, menu);
         mRefresh = menu.findItem(R.id.menu_acc_summary_refresh);
-        assert mRefresh != null;
+        if (mRefresh == null) throw new AssertionError();
+
+        mShowHiddenAccounts = menu.findItem(R.id.menu_acc_summary_show_hidden);
+        if (mShowHiddenAccounts == null) throw new AssertionError();
+
+        sBindPreferenceSummaryToValueListener =
+                new SharedPreferences.OnSharedPreferenceChangeListener() {
+                    @Override
+                    public
+                    void onSharedPreferenceChanged(SharedPreferences preference, String value) {
+                        mShowHiddenAccounts
+                                .setChecked(preference.getBoolean("show_hidden_accounts", false));
+                    }
+                };
+        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
+        pref.registerOnSharedPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
+
+        mShowHiddenAccounts.setChecked(pref.getBoolean("show_hidden_accounts", false));
+
         return true;
     }
 
@@ -110,7 +162,7 @@ public class AccountSummary extends AppCompatActivity {
         // Handle action bar item clicks here. The action bar will
         // automatically handle clicks on the Home/Up button, so long
         // as you specify a parent activity in AndroidManifest.xml.
-        int id = item.getItemId();
+//        int id = item.getItemId();
 
         //noinspection SimplifiableIfStatement
         //if (id == R.id.action_settings) {
@@ -124,19 +176,21 @@ public class AccountSummary extends AppCompatActivity {
         update_accounts(true);
     }
 
-    private void prepare_db() {
-        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
-            MobileLedgerDB.setDb_filename(this.getApplicationInfo().deviceProtectedDataDir + "/" + MobileLedgerDB.DATABASE_NAME);
-        }
-        else {
-            MobileLedgerDB.setDb_filename(MobileLedgerDB.DATABASE_NAME);
-        }
-        MobileLedgerDB.initDB();
+    public
+    void onShowHiddenAccountsClicked(MenuItem mi) {
+        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
+        boolean flag = pref.getBoolean("show_hidden_accounts", false);
 
-        MobileLedgerDB.applyRevisions(getResources(), getPackageName());
+        SharedPreferences.Editor editor = pref.edit();
+        editor.putBoolean("show_hidden_accounts", !flag);
+        Log.d("pref", "Setting show_hidden_accounts to " + (flag ? "false" : "true"));
+        editor.apply();
 
-        account_list_last_updated = MobileLedgerDB.get_option_value("last_refresh", (long) 0);
+        update_account_table();
+    }
 
+    private void prepare_db() {
+        account_list_last_updated = dbh.get_option_value("last_refresh", (long) 0);
     }
 
     private void update_accounts(boolean force) {
@@ -148,7 +202,7 @@ public class AccountSummary extends AppCompatActivity {
     }
 
     private void update_accounts() {
-        mRefresh.setVisible(false);
+        if (mRefresh != null) mRefresh.setVisible(false);
         Resources rm = getResources();
 
         ProgressBar pb = findViewById(R.id.progressBar);
@@ -170,14 +224,14 @@ public class AccountSummary extends AppCompatActivity {
             protected void onPostExecute(Void result) {
                 pb.setVisibility(GONE);
                 pt.setVisibility(GONE);
-                mRefresh.setVisible(true);
+                if (mRefresh != null) mRefresh.setVisible(true);
                 if (this.error != 0) {
                     String err_text = rm.getString(this.error);
                     Log.d("visual", String.format("showing snackbar: %s", err_text));
                     Snackbar.make(drawer, err_text, Snackbar.LENGTH_LONG ).show();
                 }
                 else {
-                    set_option_value("last_refresh", new Date().getTime() );
+                    dbh.set_option_value("last_refresh", new Date().getTime() );
                     update_account_table();
                 }
             }
@@ -192,51 +246,133 @@ public class AccountSummary extends AppCompatActivity {
         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
     }
 
+    Pattern higher_account = Pattern.compile("^[^:]+:");
+
+    private String strip_higher_accounts(String acc_name, int[] count) {
+        count[0] = 0;
+        while (true) {
+            Matcher m = higher_account.matcher(acc_name);
+            if (m.find()) {
+                count[0]++;
+                acc_name = m.replaceFirst("");
+            }
+            else break;
+        }
+
+        return acc_name;
+    }
+
+    public void hideAccountClicked(MenuItem item) {
+        try(SQLiteDatabase db = dbh.getWritableDatabase()) {
+            db.execSQL("update accounts set hidden=1 where name=?", new Object[]{clickedAccountRow.getAccountName()});
+        }
+        update_account_table();
+    }
+
     @SuppressLint("DefaultLocale")
     private void update_account_table() {
         LinearLayout root = findViewById(R.id.account_root);
         root.removeAllViewsInLayout();
 
-        try (Cursor cursor = db.rawQuery("SELECT name FROM accounts ORDER BY name;", null)) {
-            boolean even = false;
-            while (cursor.moveToNext()) {
-                String acc_name = cursor.getString(0);
-
-                TableLayout t = new TableLayout(this);
-                TableRow r = new TableRow(this);
-                r.setLayoutParams(new TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
-                r.setGravity(Gravity.CENTER_VERTICAL);
-                r.setPadding(getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin), dp2px(4), getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin), dp2px(4));
-                if (even)
-                    r.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg, getTheme()));
-                even = !even;
-
-                TextView acc_tv = new TextView(this, null, R.style.account_summary_account_name);
-                acc_tv.setLayoutParams(new TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 9f));
-                acc_tv.setText(acc_name);
-                r.addView(acc_tv);
-
-                TextView amt_tv = new TextView(this, null, R.style.account_summary_amounts);
-                amt_tv.setLayoutParams(new TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1f));
-                amt_tv.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
-                amt_tv.setGravity(Gravity.CENTER);
-                amt_tv.setMinWidth(dp2px(40f));
-                StringBuilder amt_text = new StringBuilder();
-                try (Cursor cAmounts = db.rawQuery("SELECT currency, value FROM account_values WHERE account = ?", new String[]{acc_name})) {
-                    while (cAmounts.moveToNext()) {
-                        String curr = cAmounts.getString(0);
-                        Float amt = cAmounts.getFloat(1);
-                        if (amt_text.length() != 0) amt_text.append('\n');
-                        amt_text.append(String.format("%s %1.2f", curr, amt));
+        View.OnCreateContextMenuListener ccml = new View.OnCreateContextMenuListener() {
+            @Override
+            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
+                clickedAccountRow = (AccountRowLayout) v;
+                getMenuInflater().inflate(R.menu.account_summary_account_menu, menu);
+            }
+        };
+
+        int rowHeight =
+                (int) (getTheme().obtainStyledAttributes(new int[]{android.R.attr.actionBarSize})
+                        .getDimensionPixelSize(0, dp2px(56)) * 0.75);
+
+        boolean showingHiddenAccounts = PreferenceManager.getDefaultSharedPreferences(this)
+                .getBoolean("show_hidden_accounts", false);
+        Log.d("pref", "show_hidden_accounts is " + (showingHiddenAccounts ? "true" : "false"));
+
+        try(SQLiteDatabase db = dbh.getReadableDatabase()) {
+            try (Cursor cursor = db
+                    .rawQuery("SELECT name, hidden FROM accounts ORDER BY name;", null))
+            {
+                boolean even = false;
+                String skippingAccountName = null;
+                while (cursor.moveToNext()) {
+                    String acc_name = cursor.getString(0);
+                    if (skippingAccountName != null) {
+                        if (acc_name.startsWith(skippingAccountName + ":")) continue;
+
+                        skippingAccountName = null;
+                    }
+
+                    boolean is_hidden = cursor.getInt(1) == 1;
+
+                    if (!showingHiddenAccounts && is_hidden) {
+                        skippingAccountName = acc_name;
+                        continue;
                     }
-                }
-                amt_tv.setText(amt_text.toString());
 
-                r.addView(amt_tv);
+                    LinearLayout r = new AccountRowLayout(this, acc_name);
+                    r.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
+                            ViewGroup.LayoutParams.WRAP_CONTENT));
+                    r.setGravity(Gravity.CENTER_VERTICAL);
+                    r.setPadding(getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin), dp2px(3),
+                            getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin),
+                            dp2px(4));
+                    r.setMinimumHeight(rowHeight);
+
+                    if (even) {
+                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+                            r.setBackgroundColor(
+                                    getResources().getColor(R.color.table_row_even_bg, getTheme()));
+                        }
+                        else {
+                            r.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg));
+                        }
+                    }
+                    even = !even;
+                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+                        r.setContextClickable(true);
+                    }
+                    r.setOnCreateContextMenuListener(ccml);
+
+
+                    TextView acc_tv = new TextView(this, null, R.style.account_summary_account_name);
+                    acc_tv.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
+                            ViewGroup.LayoutParams.MATCH_PARENT, 5f));
+                    acc_tv.setGravity(Gravity.CENTER_VERTICAL);
+                    int[] indent_level = new int[]{0};
+                    String short_acc_name = strip_higher_accounts(acc_name, indent_level);
+                    acc_tv.setPadding(indent_level[0] * getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin) / 2, 0, 0,
+                            0);
+                    acc_tv.setText(short_acc_name);
+                    if (is_hidden) acc_tv.setTypeface(null, Typeface.ITALIC);
+                    r.addView(acc_tv);
+
+                    TextView amt_tv = new TextView(this, null, R.style.account_summary_amounts);
+                    amt_tv.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
+                            ViewGroup.LayoutParams.MATCH_PARENT, 1f));
+                    amt_tv.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
+                    amt_tv.setGravity(Gravity.CENTER_VERTICAL);
+//                amt_tv.setGravity(Gravity.CENTER);
+                    amt_tv.setMinWidth(dp2px(60f));
+                    StringBuilder amt_text = new StringBuilder();
+                    try (Cursor cAmounts = db.rawQuery(
+                            "SELECT currency, value FROM account_values WHERE account = ?", new String[]{acc_name}))
+                    {
+                        while (cAmounts.moveToNext()) {
+                            String curr = cAmounts.getString(0);
+                            Float amt = cAmounts.getFloat(1);
+                            if (amt_text.length() != 0) amt_text.append('\n');
+                            amt_text.append(String.format("%s %,1.2f", curr, amt));
+                        }
+                    }
+                    amt_tv.setText(amt_text.toString());
+                    if (is_hidden) amt_tv.setTypeface(null, Typeface.ITALIC);
 
-                t.addView(r);
+                    r.addView(amt_tv);
 
-                root.addView(t);
+                    root.addView(r);
+                }
             }
         }
     }