2 * Copyright © 2019 Damyan Ivanov.
3 * This file is part of Mobile-Ledger.
4 * Mobile-Ledger is free software: you can distribute it and/or modify it
5 * under the term of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your opinion), any later version.
9 * Mobile-Ledger is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License terms for details.
14 * You should have received a copy of the GNU General Public License
15 * along with Mobile-Ledger. If not, see <https://www.gnu.org/licenses/>.
18 package net.ktnx.mobileledger.ui.activity;
20 import android.content.Intent;
21 import android.content.SharedPreferences;
22 import android.content.pm.PackageInfo;
23 import android.os.Build;
24 import android.os.Bundle;
25 import android.support.annotation.ColorInt;
26 import android.support.v4.app.Fragment;
27 import android.support.v4.app.FragmentManager;
28 import android.support.v4.app.FragmentPagerAdapter;
29 import android.support.v4.view.GravityCompat;
30 import android.support.v4.view.ViewPager;
31 import android.support.v4.widget.DrawerLayout;
32 import android.support.v7.app.ActionBarDrawerToggle;
33 import android.support.v7.app.AppCompatActivity;
34 import android.support.v7.widget.Toolbar;
35 import android.util.Log;
36 import android.view.ContextMenu;
37 import android.view.MenuItem;
38 import android.view.View;
39 import android.widget.LinearLayout;
40 import android.widget.ProgressBar;
41 import android.widget.TextView;
43 import net.ktnx.mobileledger.R;
44 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
45 import net.ktnx.mobileledger.model.Data;
46 import net.ktnx.mobileledger.model.LedgerAccount;
47 import net.ktnx.mobileledger.model.MobileLedgerProfile;
48 import net.ktnx.mobileledger.ui.MobileLedgerListFragment;
49 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
50 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
51 import net.ktnx.mobileledger.utils.MLDB;
53 import java.lang.ref.WeakReference;
54 import java.time.ZoneId;
55 import java.time.format.DateTimeFormatter;
56 import java.util.Date;
57 import java.util.Observable;
58 import java.util.Observer;
60 public class MainActivity extends AppCompatActivity {
61 public MobileLedgerListFragment currentFragment = null;
63 private AccountSummaryFragment accountSummaryFragment;
64 private TransactionListFragment transactionListFragment;
65 private FragmentManager fragmentManager;
66 private TextView tvLastUpdate;
67 private RetrieveTransactionsTask retrieveTransactionsTask;
68 private View bTransactionListCancelDownload;
69 private ProgressBar progressBar;
70 private LinearLayout progressLayout;
71 private SectionsPagerAdapter mSectionsPagerAdapter;
72 private ViewPager mViewPager;
75 protected void onStart() {
78 Data.lastUpdateDate.set(null);
79 updateLastUpdateTextFromDB();
80 Date lastUpdate = Data.lastUpdateDate.get();
82 long now = new Date().getTime();
83 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
84 if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
86 String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
87 lastUpdate.getTime() / 1000f, now / 1000f));
89 scheduleTransactionListRetrieval();
93 protected void onCreate(Bundle savedInstanceState) {
94 super.onCreate(savedInstanceState);
95 setContentView(R.layout.activity_main);
96 Toolbar toolbar = findViewById(R.id.toolbar);
97 setSupportActionBar(toolbar);
99 Data.profile.addObserver(new Observer() {
101 public void update(Observable o, Object arg) {
102 MobileLedgerProfile profile = Data.profile.get();
103 runOnUiThread(() -> {
104 if (profile == null) toolbar.setSubtitle("");
105 else toolbar.setSubtitle(profile.getName());
112 drawer = findViewById(R.id.drawer_layout);
113 ActionBarDrawerToggle toggle =
114 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
115 R.string.navigation_drawer_close);
116 drawer.addDrawerListener(toggle);
119 android.widget.TextView ver = drawer.findViewById(R.id.drawer_version_text);
123 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
124 ver.setText(pi.versionName);
126 catch (Exception e) {
130 tvLastUpdate = findViewById(R.id.transactions_last_update);
132 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
133 progressBar = findViewById(R.id.transaction_list_progress_bar);
134 if (progressBar == null)
135 throw new RuntimeException("Can't get hold on the transaction value progress bar");
136 progressLayout = findViewById(R.id.transaction_progress_layout);
137 if (progressLayout == null) throw new RuntimeException(
138 "Can't get hold on the transaction value progress bar layout");
140 fragmentManager = getSupportFragmentManager();
141 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
143 mViewPager = findViewById(R.id.root_frame);
144 mViewPager.setAdapter(mSectionsPagerAdapter);
145 mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
147 public void onPageSelected(int position) {
150 markDrawerItemCurrent(R.id.nav_account_summary);
153 markDrawerItemCurrent(R.id.nav_latest_transactions);
156 Log.e("MainActivity", String.format("Unexpected page index %d", position));
159 super.onPageSelected(position);
163 Data.lastUpdateDate.addObserver(new Observer() {
165 public void update(Observable o, Object arg) {
166 Log.d("main", "lastUpdateDate changed");
167 runOnUiThread(() -> {
168 Date date = Data.lastUpdateDate.get();
170 tvLastUpdate.setText(R.string.transaction_last_update_never);
173 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
174 tvLastUpdate.setText(date.toInstant().atZone(ZoneId.systemDefault())
175 .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
178 tvLastUpdate.setText(date.toLocaleString());
185 private void setupProfile() {
186 Data.profiles.setList(MobileLedgerProfile.loadAllFromDB());
187 MobileLedgerProfile profile = null;
189 String profileUUID = MLDB.get_option_value(MLDB.OPT_PROFILE_UUID, null);
190 if (profileUUID == null) {
191 if (Data.profiles.isEmpty()) {
192 Data.profiles.setList(MobileLedgerProfile.createInitialProfileList());
193 profile = Data.profiles.get(0);
195 SharedPreferences backend = getSharedPreferences("backend", MODE_PRIVATE);
196 Log.d("profiles", "Migrating from preferences to profiles");
197 // migration to multiple profiles
198 if (profile.getUrl().isEmpty()) {
200 Intent intent = new Intent(this, ProfileListActivity.class);
201 startActivity(intent);
203 profile.setUrl(backend.getString("backend_url", ""));
204 profile.setAuthEnabled(backend.getBoolean("backend_use_http_auth", false));
205 profile.setAuthUserName(backend.getString("backend_auth_user", null));
206 profile.setAuthPassword(backend.getString("backend_auth_password", null));
208 SharedPreferences.Editor editor = backend.edit();
214 profile = MobileLedgerProfile.loadUUIDFromDB(profileUUID);
217 if (profile == null) profile = Data.profiles.get(0);
219 if (profile == null) throw new AssertionError("profile must have a value");
221 Data.profile.set(profile);
222 MLDB.set_option_value(MLDB.OPT_PROFILE_UUID, profile.getUuid());
224 if (profile.getUrl().isEmpty()) {
225 Intent intent = new Intent(this, ProfileListActivity.class);
226 Bundle args = new Bundle();
227 args.putInt(ProfileListActivity.ARG_ACTION, ProfileListActivity.ACTION_EDIT_PROFILE);
228 args.putInt(ProfileListActivity.ARG_PROFILE_INDEX, 0);
229 intent.putExtras(args);
230 startActivity(intent, args);
233 public void fab_new_transaction_clicked(View view) {
234 Intent intent = new Intent(this, NewTransactionActivity.class);
235 startActivity(intent);
236 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
239 public void nav_exit_clicked(View view) {
240 Log.w("app", "exiting");
244 public void nav_settings_clicked(View view) {
245 Intent intent = new Intent(this, SettingsActivity.class);
246 startActivity(intent);
248 public void markDrawerItemCurrent(int id) {
249 TextView item = drawer.findViewById(id);
250 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
251 item.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg, getTheme()));
254 item.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg));
257 setTitle(item.getText());
259 @ColorInt int transparent = getResources().getColor(android.R.color.transparent);
261 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
262 for (int i = 0; i < actions.getChildCount(); i++) {
263 View view = actions.getChildAt(i);
264 if (view.getId() != id) {
265 view.setBackgroundColor(transparent);
269 public void onOptionsMenuClicked(MenuItem menuItem) {
270 ContextMenu.ContextMenuInfo info = menuItem.getMenuInfo();
271 switch (menuItem.getItemId()) {
272 case R.id.menu_acc_summary_cancel_selection:
273 if (accountSummaryFragment != null)
274 accountSummaryFragment.onCancelAccSelection(menuItem);
276 case R.id.menu_acc_summary_confirm_selection:
277 if (accountSummaryFragment != null)
278 accountSummaryFragment.onConfirmAccSelection(menuItem);
280 case R.id.menu_acc_summary_only_starred:
281 if (accountSummaryFragment != null)
282 accountSummaryFragment.onShowOnlyStarredClicked(menuItem);
284 case R.id.menu_transaction_list_filter:
285 if (transactionListFragment != null)
286 transactionListFragment.onShowFilterClick(menuItem);
289 Log.e("menu", String.format("Menu item %d not handled", menuItem.getItemId()));
292 public void onViewClicked(View view) {
293 switch (view.getId()) {
294 case R.id.clearAccountNameFilter:
295 if (transactionListFragment != null)
296 transactionListFragment.onClearAccountNameClick(view);
299 Log.e("click", String.format("View %d click not handled", view.getId()));
302 public void onAccountSummaryClicked(View view) {
303 drawer.closeDrawers();
305 showAccountSummaryFragment();
307 private void showAccountSummaryFragment() {
308 mViewPager.setCurrentItem(0, true);
309 // FragmentTransaction ft = fragmentManager.beginTransaction();
310 // accountSummaryFragment = new AccountSummaryFragment();
311 // ft.replace(R.id.root_frame, accountSummaryFragment);
313 // currentFragment = accountSummaryFragment;
315 public void onLatestTransactionsClicked(View view) {
316 drawer.closeDrawers();
318 showTransactionsFragment(null);
320 private void resetFragmentBackStack() {
321 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
323 private void showTransactionsFragment(LedgerAccount account) {
324 mViewPager.setCurrentItem(1, true);
325 // FragmentTransaction ft = fragmentManager.beginTransaction();
326 // if (transactionListFragment == null) {
327 // Log.d("flow", "MainActivity creating TransactionListFragment");
328 // transactionListFragment = new TransactionListFragment();
330 // Bundle bundle = new Bundle();
331 // if (account != null) {
332 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
333 // account.getName());
335 // transactionListFragment.setArguments(bundle);
336 // ft.replace(R.id.root_frame, transactionListFragment);
337 // if (account != null)
338 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
341 // currentFragment = transactionListFragment;
343 public void showAccountTransactions(LedgerAccount account) {
344 showTransactionsFragment(account);
347 public void onBackPressed() {
348 DrawerLayout drawer = findViewById(R.id.drawer_layout);
349 if (drawer.isDrawerOpen(GravityCompat.START)) {
350 drawer.closeDrawer(GravityCompat.START);
354 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
356 super.onBackPressed();
359 public void updateLastUpdateTextFromDB() {
361 long last_update = Data.profile.get().get_option_value(MLDB.OPT_LAST_SCRAPE, 0L);
363 Log.d("transactions", String.format("Last update = %d", last_update));
364 if (last_update == 0) {
365 Data.lastUpdateDate.set(null);
368 Data.lastUpdateDate.set(new Date(last_update));
372 public void scheduleTransactionListRetrieval() {
373 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
375 retrieveTransactionsTask.execute();
376 bTransactionListCancelDownload.setEnabled(true);
378 public void onStopTransactionRefreshClick(View view) {
379 Log.d("interactive", "Cancelling transactions refresh");
380 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
381 bTransactionListCancelDownload.setEnabled(false);
383 public void onRetrieveDone(boolean success) {
384 progressLayout.setVisibility(View.GONE);
385 updateLastUpdateTextFromDB();
387 public void onRetrieveStart() {
388 progressBar.setIndeterminate(true);
389 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
390 else progressBar.setProgress(0);
391 progressLayout.setVisibility(View.VISIBLE);
393 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
394 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
395 (progress.getTotal() == 0))
397 progressBar.setIndeterminate(true);
400 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
401 progressBar.setMin(0);
403 progressBar.setMax(progress.getTotal());
404 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
405 progressBar.setProgress(progress.getProgress(), true);
407 else progressBar.setProgress(progress.getProgress());
408 progressBar.setIndeterminate(false);
411 public void nav_profiles_clicked(View view) {
412 drawer.closeDrawers();
413 Intent intent = new Intent(this, ProfileListActivity.class);
414 startActivity(intent);
416 public class SectionsPagerAdapter extends FragmentPagerAdapter {
418 public SectionsPagerAdapter(FragmentManager fm) {
423 public Fragment getItem(int position) {
424 Log.d("main", String.format("Switching to gragment %d", position));
427 return new AccountSummaryFragment();
429 return new TransactionListFragment();
431 throw new IllegalStateException(
432 String.format("Unexpected fragment index: " + "%d", position));
437 public int getCount() {