]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/AccountSummary.java
center vertically the text in the account row
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / AccountSummary.java
1 package net.ktnx.mobileledger;
2
3 import android.annotation.SuppressLint;
4 import android.content.Intent;
5 import android.content.pm.PackageInfo;
6 import android.content.res.Resources;
7 import android.database.Cursor;
8 import android.os.Build;
9 import android.os.Bundle;
10 import android.preference.PreferenceManager;
11 import android.support.design.widget.Snackbar;
12 import android.support.v4.view.GravityCompat;
13 import android.support.v4.widget.DrawerLayout;
14 import android.support.v7.app.ActionBarDrawerToggle;
15 import android.support.v7.app.AppCompatActivity;
16 import android.support.v7.widget.Toolbar;
17 import android.util.Log;
18 import android.util.TypedValue;
19 import android.view.Gravity;
20 import android.view.Menu;
21 import android.view.MenuItem;
22 import android.view.View;
23 import android.view.ViewGroup;
24 import android.widget.EditText;
25 import android.widget.LinearLayout;
26 import android.widget.ProgressBar;
27 import android.widget.TableLayout;
28 import android.widget.TableRow;
29 import android.widget.TextView;
30
31 import java.util.Date;
32
33 import static android.view.View.GONE;
34 import static net.ktnx.mobileledger.MobileLedgerDB.db;
35 import static net.ktnx.mobileledger.MobileLedgerDB.set_option_value;
36
37 public class AccountSummary extends AppCompatActivity {
38     DrawerLayout drawer;
39
40     private static long account_list_last_updated;
41     private static boolean account_list_needs_update = true;
42     public static void preferences_changed() {
43         account_list_needs_update = true;
44     }
45     MenuItem mRefresh;
46
47     @Override
48     protected void onCreate(Bundle savedInstanceState) {
49         super.onCreate(savedInstanceState);
50         setContentView(R.layout.activity_account_summary);
51         Toolbar toolbar = findViewById(R.id.toolbar);
52         setSupportActionBar(toolbar);
53
54         drawer = findViewById(R.id.drawer_layout);
55         ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
56                 this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
57         drawer.addDrawerListener(toggle);
58         toggle.syncState();
59
60         android.widget.TextView ver = drawer.findViewById(R.id.drawer_version_text);
61
62         try {
63             PackageInfo pi = getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
64             ver.setText(pi.versionName);
65         } catch (Exception e) {
66             e.printStackTrace();
67         }
68
69         prepare_db();
70         update_account_table();
71         update_accounts(false);
72     }
73
74     public void fab_new_transaction_clicked(View view) {
75         Intent intent = new Intent(this, NewTransactionActivity.class);
76         startActivity(intent);
77     }
78
79     public void nav_exit_clicked(View view) {
80         Log.w("mobileledger", "exiting");
81         finish();
82     }
83
84     public void nav_settings_clicked(View view) {
85         Intent intent = new Intent(this, SettingsActivity.class);
86         startActivity(intent);
87     }
88
89     @Override
90     public void onBackPressed() {
91         DrawerLayout drawer = findViewById(R.id.drawer_layout);
92         if (drawer.isDrawerOpen(GravityCompat.START)) {
93             drawer.closeDrawer(GravityCompat.START);
94         } else {
95             super.onBackPressed();
96         }
97     }
98
99     @Override
100     public boolean onCreateOptionsMenu(Menu menu) {
101         // Inflate the menu; this adds items to the action bar if it is present.
102         getMenuInflater().inflate(R.menu.account_summary, menu);
103         mRefresh = menu.findItem(R.id.menu_acc_summary_refresh);
104         assert mRefresh != null;
105         return true;
106     }
107
108     @Override
109     public boolean onOptionsItemSelected(MenuItem item) {
110         // Handle action bar item clicks here. The action bar will
111         // automatically handle clicks on the Home/Up button, so long
112         // as you specify a parent activity in AndroidManifest.xml.
113         int id = item.getItemId();
114
115         //noinspection SimplifiableIfStatement
116         //if (id == R.id.action_settings) {
117         //    return true;
118         // }
119
120         return super.onOptionsItemSelected(item);
121     }
122
123     public void onRefreshAccountSummaryClicked(MenuItem mi) {
124         update_accounts(true);
125     }
126
127     private void prepare_db() {
128         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
129             MobileLedgerDB.setDb_filename(this.getApplicationInfo().deviceProtectedDataDir + "/" + MobileLedgerDB.DATABASE_NAME);
130         }
131         else {
132             MobileLedgerDB.setDb_filename(MobileLedgerDB.DATABASE_NAME);
133         }
134         MobileLedgerDB.initDB();
135
136         MobileLedgerDB.applyRevisions(getResources(), getPackageName());
137
138         account_list_last_updated = MobileLedgerDB.get_option_value("last_refresh", (long) 0);
139
140     }
141
142     private void update_accounts(boolean force) {
143         long now = new Date().getTime();
144         if ((now > (account_list_last_updated + (24 * 3600*1000))) || force) {
145             Log.d("db", "accounts last updated at " + account_list_last_updated+" and now is " + now+". re-fetching");
146             update_accounts();
147         }
148     }
149
150     private void update_accounts() {
151         mRefresh.setVisible(false);
152         Resources rm = getResources();
153
154         ProgressBar pb = findViewById(R.id.progressBar);
155         pb.setVisibility(View.VISIBLE);
156         TextView pt = findViewById(R.id.textProgress);
157         pt.setVisibility(View.VISIBLE);
158         pb.setIndeterminate(true);
159
160         RetrieveAccountsTask task = new RetrieveAccountsTask() {
161             @Override
162             protected void onProgressUpdate(Integer... values) {
163                 if ( values[0] == 0 )
164                     pt.setText(R.string.progress_connecting);
165                 else
166                     pt.setText(String.format(getResources().getString(R.string.progress_N_accounts_loaded), values[0]));
167             }
168
169             @Override
170             protected void onPostExecute(Void result) {
171                 pb.setVisibility(GONE);
172                 pt.setVisibility(GONE);
173                 mRefresh.setVisible(true);
174                 if (this.error != 0) {
175                     String err_text = rm.getString(this.error);
176                     Log.d("visual", String.format("showing snackbar: %s", err_text));
177                     Snackbar.make(drawer, err_text, Snackbar.LENGTH_LONG ).show();
178                 }
179                 else {
180                     set_option_value("last_refresh", new Date().getTime() );
181                     update_account_table();
182                 }
183             }
184         };
185
186         task.setPref(PreferenceManager.getDefaultSharedPreferences(this));
187         task.execute();
188
189     }
190
191     public int dp2px(float dp) {
192         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
193     }
194
195     @SuppressLint("DefaultLocale")
196     private void update_account_table() {
197         LinearLayout root = findViewById(R.id.account_root);
198         root.removeAllViewsInLayout();
199
200         try (Cursor cursor = db.rawQuery("SELECT name FROM accounts ORDER BY name;", null)) {
201             boolean even = false;
202             while (cursor.moveToNext()) {
203                 String acc_name = cursor.getString(0);
204
205                 TableLayout t = new TableLayout(this);
206                 TableRow r = new TableRow(this);
207                 r.setLayoutParams(new TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
208                 r.setGravity(Gravity.CENTER_VERTICAL);
209                 r.setPadding(getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin), dp2px(4), getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin), dp2px(4));
210                 if (even)
211                     r.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg, getTheme()));
212                 even = !even;
213
214                 TextView acc_tv = new TextView(this, null, R.style.account_summary_account_name);
215                 acc_tv.setLayoutParams(new TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 9f));
216                 acc_tv.setText(acc_name);
217                 r.addView(acc_tv);
218
219                 TextView amt_tv = new TextView(this, null, R.style.account_summary_amounts);
220                 amt_tv.setLayoutParams(new TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1f));
221                 amt_tv.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
222                 amt_tv.setGravity(Gravity.CENTER);
223                 amt_tv.setMinWidth(dp2px(40f));
224                 StringBuilder amt_text = new StringBuilder();
225                 try (Cursor cAmounts = db.rawQuery("SELECT currency, value FROM account_values WHERE account = ?", new String[]{acc_name})) {
226                     while (cAmounts.moveToNext()) {
227                         String curr = cAmounts.getString(0);
228                         Float amt = cAmounts.getFloat(1);
229                         if (amt_text.length() != 0) amt_text.append('\n');
230                         amt_text.append(String.format("%s %1.2f", curr, amt));
231                     }
232                 }
233                 amt_tv.setText(amt_text.toString());
234
235                 r.addView(amt_tv);
236
237                 t.addView(r);
238
239                 root.addView(t);
240             }
241         }
242     }
243 }