1 package net.ktnx.mobileledger;
3 import android.annotation.SuppressLint;
4 import android.content.Intent;
5 import android.content.SharedPreferences;
6 import android.content.pm.PackageInfo;
7 import android.content.res.Resources;
8 import android.database.Cursor;
9 import android.graphics.Typeface;
10 import android.os.Build;
11 import android.os.Bundle;
12 import android.preference.PreferenceManager;
13 import android.support.design.widget.Snackbar;
14 import android.support.v4.view.GravityCompat;
15 import android.support.v4.widget.DrawerLayout;
16 import android.support.v7.app.ActionBarDrawerToggle;
17 import android.support.v7.app.AppCompatActivity;
18 import android.support.v7.widget.Toolbar;
19 import android.util.Log;
20 import android.util.TypedValue;
21 import android.view.ContextMenu;
22 import android.view.Gravity;
23 import android.view.Menu;
24 import android.view.MenuItem;
25 import android.view.View;
26 import android.view.ViewGroup;
27 import android.widget.EditText;
28 import android.widget.LinearLayout;
29 import android.widget.ProgressBar;
30 import android.widget.TextView;
32 import java.util.Date;
33 import java.util.regex.Matcher;
34 import java.util.regex.Pattern;
36 import static android.view.View.GONE;
37 import static net.ktnx.mobileledger.MobileLedgerDB.db;
38 import static net.ktnx.mobileledger.MobileLedgerDB.set_option_value;
40 public class AccountSummary extends AppCompatActivity {
43 private static long account_list_last_updated;
44 private static boolean account_list_needs_update = true;
45 MenuItem mShowHiddenAccounts;
46 SharedPreferences.OnSharedPreferenceChangeListener sBindPreferenceSummaryToValueListener;
47 private AccountRowLayout clickedAccountRow;
49 public static void preferences_changed() {
50 account_list_needs_update = true;
55 protected void onCreate(Bundle savedInstanceState) {
56 super.onCreate(savedInstanceState);
57 setContentView(R.layout.activity_account_summary);
58 Toolbar toolbar = findViewById(R.id.toolbar);
59 setSupportActionBar(toolbar);
61 drawer = findViewById(R.id.drawer_layout);
62 ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
63 this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
64 drawer.addDrawerListener(toggle);
67 android.widget.TextView ver = drawer.findViewById(R.id.drawer_version_text);
70 PackageInfo pi = getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
71 ver.setText(pi.versionName);
72 } catch (Exception e) {
77 update_account_table();
78 update_accounts(false);
82 protected void onStart() {
84 LinearLayout grp = drawer.findViewById(R.id.nav_actions);
85 for (int i = 0; i < grp.getChildCount(); i++) {
86 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
87 grp.getChildAt(i).setBackgroundColor(
88 getResources().getColor(R.color.drawer_background, getTheme()));
92 .setBackgroundColor(getResources().getColor(R.color.drawer_background));
95 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
96 drawer.findViewById(R.id.nav_account_summary).setBackgroundColor(
97 getResources().getColor(R.color.table_row_even_bg, getTheme()));
100 drawer.findViewById(R.id.nav_account_summary)
101 .setBackgroundColor(getResources().getColor(R.color.table_row_even_bg));
105 public void fab_new_transaction_clicked(View view) {
106 Intent intent = new Intent(this, NewTransactionActivity.class);
107 startActivity(intent);
108 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
111 public void nav_exit_clicked(View view) {
112 Log.w("mobileledger", "exiting");
116 public void nav_settings_clicked(View view) {
117 Intent intent = new Intent(this, SettingsActivity.class);
118 startActivity(intent);
122 public void onBackPressed() {
123 DrawerLayout drawer = findViewById(R.id.drawer_layout);
124 if (drawer.isDrawerOpen(GravityCompat.START)) {
125 drawer.closeDrawer(GravityCompat.START);
127 super.onBackPressed();
132 public boolean onCreateOptionsMenu(Menu menu) {
133 // Inflate the menu; this adds items to the action bar if it is present.
134 getMenuInflater().inflate(R.menu.account_summary, menu);
135 mRefresh = menu.findItem(R.id.menu_acc_summary_refresh);
136 if (mRefresh == null) throw new AssertionError();
138 mShowHiddenAccounts = menu.findItem(R.id.menu_acc_summary_show_hidden);
139 if (mShowHiddenAccounts == null) throw new AssertionError();
141 sBindPreferenceSummaryToValueListener =
142 new SharedPreferences.OnSharedPreferenceChangeListener() {
145 void onSharedPreferenceChanged(SharedPreferences preference, String value) {
147 .setChecked(preference.getBoolean("show_hidden_accounts", false));
150 SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
151 pref.registerOnSharedPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
153 mShowHiddenAccounts.setChecked(pref.getBoolean("show_hidden_accounts", false));
159 public boolean onOptionsItemSelected(MenuItem item) {
160 // Handle action bar item clicks here. The action bar will
161 // automatically handle clicks on the Home/Up button, so long
162 // as you specify a parent activity in AndroidManifest.xml.
163 // int id = item.getItemId();
165 //noinspection SimplifiableIfStatement
166 //if (id == R.id.action_settings) {
170 return super.onOptionsItemSelected(item);
173 public void onRefreshAccountSummaryClicked(MenuItem mi) {
174 update_accounts(true);
178 void onShowHiddenAccountsClicked(MenuItem mi) {
179 SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
180 boolean flag = pref.getBoolean("show_hidden_accounts", false);
182 SharedPreferences.Editor editor = pref.edit();
183 editor.putBoolean("show_hidden_accounts", !flag);
184 Log.d("pref", "Setting show_hidden_accounts to " + (flag ? "false" : "true"));
187 update_account_table();
190 private void prepare_db() {
191 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
192 MobileLedgerDB.setDb_filename(this.getApplicationInfo().deviceProtectedDataDir + "/" + MobileLedgerDB.DATABASE_NAME);
195 MobileLedgerDB.setDb_filename(
196 this.getApplicationInfo().dataDir + "/" + MobileLedgerDB.DATABASE_NAME);
198 MobileLedgerDB.initDB(getResources(), getPackageName());
200 account_list_last_updated = MobileLedgerDB.get_option_value("last_refresh", (long) 0);
204 private void update_accounts(boolean force) {
205 long now = new Date().getTime();
206 if ((now > (account_list_last_updated + (24 * 3600*1000))) || force) {
207 Log.d("db", "accounts last updated at " + account_list_last_updated+" and now is " + now+". re-fetching");
212 private void update_accounts() {
213 if (mRefresh != null) mRefresh.setVisible(false);
214 Resources rm = getResources();
216 ProgressBar pb = findViewById(R.id.progressBar);
217 pb.setVisibility(View.VISIBLE);
218 TextView pt = findViewById(R.id.textProgress);
219 pt.setVisibility(View.VISIBLE);
220 pb.setIndeterminate(true);
222 RetrieveAccountsTask task = new RetrieveAccountsTask() {
224 protected void onProgressUpdate(Integer... values) {
225 if ( values[0] == 0 )
226 pt.setText(R.string.progress_connecting);
228 pt.setText(String.format(getResources().getString(R.string.progress_N_accounts_loaded), values[0]));
232 protected void onPostExecute(Void result) {
233 pb.setVisibility(GONE);
234 pt.setVisibility(GONE);
235 if (mRefresh != null) mRefresh.setVisible(true);
236 if (this.error != 0) {
237 String err_text = rm.getString(this.error);
238 Log.d("visual", String.format("showing snackbar: %s", err_text));
239 Snackbar.make(drawer, err_text, Snackbar.LENGTH_LONG ).show();
242 set_option_value("last_refresh", new Date().getTime() );
243 update_account_table();
248 task.setPref(PreferenceManager.getDefaultSharedPreferences(this));
253 public int dp2px(float dp) {
254 return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
257 Pattern higher_account = Pattern.compile("^[^:]+:");
259 private String strip_higher_accounts(String acc_name, int[] count) {
262 Matcher m = higher_account.matcher(acc_name);
265 acc_name = m.replaceFirst("");
273 public void hideAccountClicked(MenuItem item) {
274 db.execSQL("update accounts set hidden=1 where name=?",
275 new Object[]{clickedAccountRow.getAccountName()});
276 update_account_table();
279 @SuppressLint("DefaultLocale")
280 private void update_account_table() {
281 LinearLayout root = findViewById(R.id.account_root);
282 root.removeAllViewsInLayout();
284 View.OnCreateContextMenuListener ccml = new View.OnCreateContextMenuListener() {
286 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
287 clickedAccountRow = (AccountRowLayout) v;
288 getMenuInflater().inflate(R.menu.account_summary_account_menu, menu);
293 (int) (getTheme().obtainStyledAttributes(new int[]{android.R.attr.actionBarSize})
294 .getDimensionPixelSize(0, dp2px(56)) * 0.75);
296 boolean showingHiddenAccounts = PreferenceManager.getDefaultSharedPreferences(this)
297 .getBoolean("show_hidden_accounts", false);
298 Log.d("pref", "show_hidden_accounts is " + (showingHiddenAccounts ? "true" : "false"));
300 try (Cursor cursor = db
301 .rawQuery("SELECT name, hidden FROM accounts ORDER BY name;", null))
303 boolean even = false;
304 String skippingAccountName = null;
305 while (cursor.moveToNext()) {
306 String acc_name = cursor.getString(0);
307 if (skippingAccountName != null) {
308 if (acc_name.startsWith(skippingAccountName + ":")) continue;
310 skippingAccountName = null;
313 boolean is_hidden = cursor.getInt(1) == 1;
315 if (!showingHiddenAccounts && is_hidden) {
316 skippingAccountName = acc_name;
320 LinearLayout r = new AccountRowLayout(this, acc_name);
321 r.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
322 r.setGravity(Gravity.CENTER_VERTICAL);
323 r.setPadding(getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin), dp2px(3), getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin), dp2px(4));
324 r.setMinimumHeight(rowHeight);
327 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
328 r.setBackgroundColor(
329 getResources().getColor(R.color.table_row_even_bg, getTheme()));
332 r.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg));
336 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
337 r.setContextClickable(true);
339 r.setOnCreateContextMenuListener(ccml);
342 TextView acc_tv = new TextView(this, null, R.style.account_summary_account_name);
343 acc_tv.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 5f));
344 acc_tv.setGravity(Gravity.CENTER_VERTICAL);
345 int[] indent_level = new int[]{0};
346 String short_acc_name = strip_higher_accounts(acc_name, indent_level);
347 acc_tv.setPadding(indent_level[0] * getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin) / 2, 0, 0, 0);
348 acc_tv.setText(short_acc_name);
349 if (is_hidden) acc_tv.setTypeface(null, Typeface.ITALIC);
352 TextView amt_tv = new TextView(this, null, R.style.account_summary_amounts);
353 amt_tv.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1f));
354 amt_tv.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
355 amt_tv.setGravity(Gravity.CENTER_VERTICAL);
356 // amt_tv.setGravity(Gravity.CENTER);
357 amt_tv.setMinWidth(dp2px(60f));
358 StringBuilder amt_text = new StringBuilder();
359 try (Cursor cAmounts = db.rawQuery("SELECT currency, value FROM account_values WHERE account = ?", new String[]{acc_name})) {
360 while (cAmounts.moveToNext()) {
361 String curr = cAmounts.getString(0);
362 Float amt = cAmounts.getFloat(1);
363 if (amt_text.length() != 0) amt_text.append('\n');
364 amt_text.append(String.format("%s %,1.2f", curr, amt));
367 amt_tv.setText(amt_text.toString());
368 if (is_hidden) amt_tv.setTypeface(null, Typeface.ITALIC);