2 * Copyright © 2020 Damyan Ivanov.
3 * This file is part of MoLe.
4 * MoLe 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 * MoLe 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 MoLe. 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.content.pm.ShortcutInfo;
24 import android.content.pm.ShortcutManager;
25 import android.content.res.ColorStateList;
26 import android.graphics.Color;
27 import android.graphics.drawable.Icon;
28 import android.os.AsyncTask;
29 import android.os.Build;
30 import android.os.Bundle;
31 import android.util.Log;
32 import android.view.View;
33 import android.view.ViewGroup;
34 import android.view.animation.AnimationUtils;
35 import android.widget.LinearLayout;
36 import android.widget.ProgressBar;
37 import android.widget.TextView;
39 import androidx.annotation.NonNull;
40 import androidx.appcompat.app.ActionBarDrawerToggle;
41 import androidx.appcompat.widget.Toolbar;
42 import androidx.core.view.GravityCompat;
43 import androidx.drawerlayout.widget.DrawerLayout;
44 import androidx.fragment.app.Fragment;
45 import androidx.fragment.app.FragmentManager;
46 import androidx.fragment.app.FragmentPagerAdapter;
47 import androidx.recyclerview.widget.LinearLayoutManager;
48 import androidx.recyclerview.widget.RecyclerView;
49 import androidx.viewpager.widget.ViewPager;
51 import com.google.android.material.floatingactionbutton.FloatingActionButton;
52 import com.google.android.material.snackbar.Snackbar;
54 import net.ktnx.mobileledger.R;
55 import net.ktnx.mobileledger.async.RefreshDescriptionsTask;
56 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
57 import net.ktnx.mobileledger.model.Data;
58 import net.ktnx.mobileledger.model.LedgerAccount;
59 import net.ktnx.mobileledger.model.MobileLedgerProfile;
60 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
61 import net.ktnx.mobileledger.ui.profiles.ProfileDetailFragment;
62 import net.ktnx.mobileledger.ui.profiles.ProfilesRecyclerViewAdapter;
63 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
64 import net.ktnx.mobileledger.ui.transaction_list.TransactionListViewModel;
65 import net.ktnx.mobileledger.utils.Colors;
66 import net.ktnx.mobileledger.utils.GetOptCallback;
67 import net.ktnx.mobileledger.utils.Logger;
68 import net.ktnx.mobileledger.utils.MLDB;
70 import org.jetbrains.annotations.NotNull;
72 import java.text.DateFormat;
73 import java.util.ArrayList;
74 import java.util.Date;
75 import java.util.List;
76 import java.util.Locale;
78 import static net.ktnx.mobileledger.utils.Logger.debug;
84 public class MainActivity extends ProfileThemedActivity {
85 public static final String STATE_CURRENT_PAGE = "current_page";
86 public static final String BUNDLE_SAVED_STATE = "bundle_savedState";
87 public static final String STATE_ACC_FILTER = "account_filter";
88 private static final String PREF_THEME_ID = "themeId";
90 private View profileListHeadMore, profileListHeadCancel, profileListHeadAddProfile;
91 private View bTransactionListCancelDownload;
92 private SectionsPagerAdapter mSectionsPagerAdapter;
93 private ViewPager mViewPager;
94 private FloatingActionButton fab;
95 private ProfilesRecyclerViewAdapter mProfileListAdapter;
96 private int mCurrentPage;
97 private boolean mBackMeansToAccountList = false;
98 private Toolbar mToolbar;
99 private DrawerLayout.SimpleDrawerListener drawerListener;
100 private ActionBarDrawerToggle barDrawerToggle;
101 private ViewPager.SimpleOnPageChangeListener pageChangeListener;
102 private MobileLedgerProfile profile;
104 protected void onStart() {
107 Logger.debug("MainActivity", "onStart()");
109 mViewPager.setCurrentItem(mCurrentPage, false);
112 protected void onSaveInstanceState(@NotNull Bundle outState) {
113 super.onSaveInstanceState(outState);
114 outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
115 if (Data.accountFilter.getValue() != null)
116 outState.putString(STATE_ACC_FILTER, Data.accountFilter.getValue());
119 protected void onDestroy() {
120 mSectionsPagerAdapter = null;
121 RecyclerView root = findViewById(R.id.nav_profile_list);
123 root.setAdapter(null);
125 drawer.removeDrawerListener(drawerListener);
126 drawerListener = null;
128 drawer.removeDrawerListener(barDrawerToggle);
129 barDrawerToggle = null;
130 if (mViewPager != null)
131 mViewPager.removeOnPageChangeListener(pageChangeListener);
132 pageChangeListener = null;
136 protected void setupProfileColors() {
137 SharedPreferences prefs = getPreferences(MODE_PRIVATE);
138 int profileColor = prefs.getInt(PREF_THEME_ID, -2);
139 if (profileColor == -2)
140 profileColor = Data.retrieveCurrentThemeIdFromDb();
141 Colors.setupTheme(this, profileColor);
142 Colors.profileThemeId = profileColor;
143 storeThemeIdInPrefs(profileColor);
146 protected void onResume() {
151 protected void onCreate(Bundle savedInstanceState) {
152 debug("MainActivity", "onCreate()/entry");
153 super.onCreate(savedInstanceState);
154 debug("MainActivity", "onCreate()/after super");
155 setContentView(R.layout.activity_main);
157 fab = findViewById(R.id.btn_add_transaction);
158 profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
159 profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
160 LinearLayout profileListHeadMoreAndCancel =
161 findViewById(R.id.nav_profile_list_head_buttons);
162 profileListHeadAddProfile = findViewById(R.id.nav_new_profile_button);
163 drawer = findViewById(R.id.drawer_layout);
164 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
165 mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
166 mViewPager = findViewById(R.id.root_frame);
168 Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
169 if (extra != null && savedInstanceState == null)
170 savedInstanceState = extra;
173 mToolbar = findViewById(R.id.toolbar);
174 setSupportActionBar(mToolbar);
176 Data.profile.observe(this, this::onProfileChanged);
178 Data.profiles.observe(this, this::onProfileListChanged);
180 if (barDrawerToggle == null) {
181 barDrawerToggle = new ActionBarDrawerToggle(this, drawer, mToolbar,
182 R.string.navigation_drawer_open, R.string.navigation_drawer_close);
183 drawer.addDrawerListener(barDrawerToggle);
185 barDrawerToggle.syncState();
188 PackageInfo pi = getApplicationContext().getPackageManager()
189 .getPackageInfo(getPackageName(), 0);
190 ((TextView) findViewById(R.id.nav_upper).findViewById(
191 R.id.drawer_version_text)).setText(pi.versionName);
192 ((TextView) findViewById(R.id.no_profiles_layout).findViewById(
193 R.id.drawer_version_text)).setText(pi.versionName);
195 catch (Exception e) {
199 markDrawerItemCurrent(R.id.nav_account_summary);
201 mViewPager.setAdapter(mSectionsPagerAdapter);
203 if (pageChangeListener == null) {
204 pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
206 public void onPageSelected(int position) {
207 mCurrentPage = position;
210 markDrawerItemCurrent(R.id.nav_account_summary);
213 markDrawerItemCurrent(R.id.nav_latest_transactions);
216 Log.e("MainActivity",
217 String.format("Unexpected page index %d", position));
220 super.onPageSelected(position);
223 mViewPager.addOnPageChangeListener(pageChangeListener);
227 if (savedInstanceState != null) {
228 int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
229 if (currentPage != -1) {
230 mCurrentPage = currentPage;
232 Data.accountFilter.setValue(savedInstanceState.getString(STATE_ACC_FILTER, null));
235 Data.lastUpdateDate.observe(this, this::updateLastUpdateDisplay);
237 findViewById(R.id.btn_no_profiles_add).setOnClickListener(
238 v -> startEditProfileActivity(null));
240 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
242 findViewById(R.id.nav_new_profile_button).setOnClickListener(
243 v -> startEditProfileActivity(null));
245 RecyclerView root = findViewById(R.id.nav_profile_list);
247 throw new RuntimeException("Can't get hold on the transaction value view");
249 if (mProfileListAdapter == null)
250 mProfileListAdapter = new ProfilesRecyclerViewAdapter();
251 root.setAdapter(mProfileListAdapter);
253 mProfileListAdapter.editingProfiles.observe(this, newValue -> {
255 profileListHeadMore.setVisibility(View.GONE);
256 profileListHeadCancel.setVisibility(View.VISIBLE);
257 profileListHeadAddProfile.setVisibility(View.VISIBLE);
258 if (drawer.isDrawerOpen(GravityCompat.START)) {
259 profileListHeadMore.startAnimation(
260 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
261 profileListHeadCancel.startAnimation(
262 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
263 profileListHeadAddProfile.startAnimation(
264 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
268 profileListHeadCancel.setVisibility(View.GONE);
269 profileListHeadMore.setVisibility(View.VISIBLE);
270 profileListHeadAddProfile.setVisibility(View.GONE);
271 if (drawer.isDrawerOpen(GravityCompat.START)) {
272 profileListHeadCancel.startAnimation(
273 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
274 profileListHeadMore.startAnimation(
275 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
276 profileListHeadAddProfile.startAnimation(
277 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
281 mProfileListAdapter.notifyDataSetChanged();
284 LinearLayoutManager llm = new LinearLayoutManager(this);
286 llm.setOrientation(RecyclerView.VERTICAL);
287 root.setLayoutManager(llm);
289 profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
290 profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
291 profileListHeadMoreAndCancel.setOnClickListener(
292 (v) -> mProfileListAdapter.flipEditingProfiles());
293 if (drawerListener == null) {
294 drawerListener = new DrawerLayout.SimpleDrawerListener() {
296 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
297 if (slideOffset > 0.2)
301 public void onDrawerClosed(View drawerView) {
302 super.onDrawerClosed(drawerView);
303 mProfileListAdapter.setAnimationsEnabled(false);
304 mProfileListAdapter.editingProfiles.setValue(false);
305 Data.drawerOpen.setValue(false);
309 public void onDrawerOpened(View drawerView) {
310 super.onDrawerOpened(drawerView);
311 mProfileListAdapter.setAnimationsEnabled(true);
312 Data.drawerOpen.setValue(true);
316 drawer.addDrawerListener(drawerListener);
319 Data.drawerOpen.observe(this, open -> {
326 private void scheduleDataRetrievalIfStale(Date lastUpdate) {
327 long now = new Date().getTime();
328 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
329 if (lastUpdate == null)
330 debug("db::", "WEB data never fetched. scheduling a fetch");
332 debug("db", String.format(Locale.ENGLISH,
333 "WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
334 lastUpdate.getTime() / 1000f, now / 1000f));
336 Data.scheduleTransactionListRetrieval(this);
339 private void createShortcuts(List<MobileLedgerProfile> list) {
340 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
343 ShortcutManager sm = getSystemService(ShortcutManager.class);
344 List<ShortcutInfo> shortcuts = new ArrayList<>();
346 for (MobileLedgerProfile p : list) {
347 if (shortcuts.size() >= sm.getMaxShortcutCountPerActivity())
350 if (!p.isPostingPermitted())
353 final ShortcutInfo.Builder builder =
354 new ShortcutInfo.Builder(this, "new_transaction_" + p.getUuid());
355 ShortcutInfo si = builder.setShortLabel(p.getName())
356 .setIcon(Icon.createWithResource(this,
357 R.drawable.thick_plus_icon))
358 .setIntent(new Intent(Intent.ACTION_VIEW, null, this,
359 NewTransactionActivity.class).putExtra("profile_uuid",
366 sm.setDynamicShortcuts(shortcuts);
368 private void onProfileListChanged(List<MobileLedgerProfile> newList) {
369 if ((newList == null) || newList.isEmpty()) {
370 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
371 findViewById(R.id.main_app_layout).setVisibility(View.GONE);
375 findViewById(R.id.main_app_layout).setVisibility(View.VISIBLE);
376 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
378 findViewById(R.id.nav_profile_list).setMinimumHeight(
379 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
381 debug("profiles", "profile list changed");
382 mProfileListAdapter.notifyDataSetChanged();
384 createShortcuts(newList);
387 * called when the current profile has changed
389 private void onProfileChanged(MobileLedgerProfile profile) {
390 boolean haveProfile = profile != null;
393 setTitle(profile.getName());
395 setTitle(R.string.app_name);
397 if (this.profile != null)
398 this.profile.getAccounts()
399 .removeObservers(this);
401 this.profile = profile;
403 int newProfileTheme = haveProfile ? profile.getThemeHue() : -1;
404 if (newProfileTheme != Colors.profileThemeId) {
406 String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
408 Colors.profileThemeId = newProfileTheme;
409 profileThemeChanged();
410 // profileThemeChanged would restart the activity, so no need to reload the
415 findViewById(R.id.no_profiles_layout).setVisibility(haveProfile ? View.GONE : View.VISIBLE);
416 findViewById(R.id.pager_layout).setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
418 mProfileListAdapter.notifyDataSetChanged();
420 Data.transactions.clear();
421 debug("transactions", "requesting list reload");
422 TransactionListViewModel.scheduleTransactionListReload();
425 profile.scheduleAccountListReload();
427 if (profile.isPostingPermitted()) {
428 mToolbar.setSubtitle(null);
432 mToolbar.setSubtitle(R.string.profile_subtitle_read_only);
437 mToolbar.setSubtitle(null);
441 updateLastUpdateTextFromDB();
443 private void updateLastUpdateDisplay(Date newValue) {
444 LinearLayout l = findViewById(R.id.transactions_last_update_layout);
445 TextView v = findViewById(R.id.transactions_last_update);
446 if (newValue == null) {
447 l.setVisibility(View.INVISIBLE);
448 debug("main", "no last update date :(");
451 final String text = DateFormat.getDateTimeInstance()
454 l.setVisibility(View.VISIBLE);
455 debug("main", String.format("Date formatted: %s", text));
458 scheduleDataRetrievalIfStale(newValue);
460 private void profileThemeChanged() {
461 storeThemeIdInPrefs(profile.getThemeHue());
463 // un-hook all observed LiveData
464 Data.profile.removeObservers(this);
465 Data.profiles.removeObservers(this);
466 Data.lastUpdateDate.removeObservers(this);
470 private void storeThemeIdInPrefs(int themeId) {
471 // store the new theme id in the preferences
472 SharedPreferences prefs = getPreferences(MODE_PRIVATE);
473 SharedPreferences.Editor e = prefs.edit();
474 e.putInt(PREF_THEME_ID, themeId);
477 public void startEditProfileActivity(MobileLedgerProfile profile) {
478 Intent intent = new Intent(this, ProfileDetailActivity.class);
479 Bundle args = new Bundle();
480 if (profile != null) {
481 int index = Data.getProfileIndex(profile);
483 intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
485 intent.putExtras(args);
486 startActivity(intent, args);
488 private void setupProfile() {
489 MLDB.getOption(MLDB.OPT_PROFILE_UUID, null, new GetOptCallback() {
491 protected void onResult(String profileUUID) {
492 MobileLedgerProfile startupProfile;
494 startupProfile = Data.getProfile(profileUUID);
495 Data.setCurrentProfile(startupProfile);
499 public void fabNewTransactionClicked(View view) {
500 Intent intent = new Intent(this, NewTransactionActivity.class);
501 startActivity(intent);
502 overridePendingTransition(R.anim.slide_in_up, R.anim.dummy);
504 public void markDrawerItemCurrent(int id) {
505 TextView item = drawer.findViewById(id);
506 item.setBackgroundColor(Colors.tableRowDarkBG);
508 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
509 for (int i = 0; i < actions.getChildCount(); i++) {
510 View view = actions.getChildAt(i);
511 if (view.getId() != id) {
512 view.setBackgroundColor(Color.TRANSPARENT);
516 public void onAccountSummaryClicked(View view) {
517 drawer.closeDrawers();
519 showAccountSummaryFragment();
521 private void showAccountSummaryFragment() {
522 mViewPager.setCurrentItem(0, true);
523 Data.accountFilter.setValue(null);
525 public void onLatestTransactionsClicked(View view) {
526 drawer.closeDrawers();
528 showTransactionsFragment((String) null);
530 public void showTransactionsFragment(String accName) {
531 Data.accountFilter.setValue(accName);
532 mViewPager.setCurrentItem(1, true);
534 public void showAccountTransactions(String accountName) {
535 mBackMeansToAccountList = true;
536 showTransactionsFragment(accountName);
539 public void onBackPressed() {
540 DrawerLayout drawer = findViewById(R.id.drawer_layout);
541 if (drawer.isDrawerOpen(GravityCompat.START)) {
542 drawer.closeDrawer(GravityCompat.START);
545 if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
546 Data.accountFilter.setValue(null);
547 showAccountSummaryFragment();
548 mBackMeansToAccountList = false;
551 debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
552 getSupportFragmentManager().getBackStackEntryCount()));
554 super.onBackPressed();
558 public void updateLastUpdateTextFromDB() {
562 long last_update = profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
564 debug("transactions", String.format(Locale.ENGLISH, "Last update = %d", last_update));
565 if (last_update == 0) {
566 Data.lastUpdateDate.postValue(null);
569 Data.lastUpdateDate.postValue(new Date(last_update));
572 public void onStopTransactionRefreshClick(View view) {
573 debug("interactive", "Cancelling transactions refresh");
574 Data.stopTransactionsRetrieval();
575 bTransactionListCancelDownload.setEnabled(false);
577 public void onRetrieveDone(String error) {
578 Data.transactionRetrievalDone();
579 findViewById(R.id.transaction_progress_layout).setVisibility(View.GONE);
582 updateLastUpdateTextFromDB();
584 new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
585 TransactionListViewModel.scheduleTransactionListReload();
588 Snackbar.make(mViewPager, error, Snackbar.LENGTH_LONG)
591 public void onRetrieveStart() {
592 ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
593 bTransactionListCancelDownload.setEnabled(true);
594 ColorStateList csl = Colors.getColorStateList();
595 progressBar.setIndeterminateTintList(csl);
596 progressBar.setProgressTintList(csl);
597 progressBar.setIndeterminate(true);
598 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
599 progressBar.setProgress(0, false);
601 progressBar.setProgress(0);
602 findViewById(R.id.transaction_progress_layout).setVisibility(View.VISIBLE);
604 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
605 ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
606 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
607 (progress.getTotal() == 0))
609 progressBar.setIndeterminate(true);
612 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
613 progressBar.setMin(0);
615 progressBar.setMax(progress.getTotal());
616 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
617 progressBar.setProgress(progress.getProgress(), true);
620 progressBar.setProgress(progress.getProgress());
621 progressBar.setIndeterminate(false);
624 public void fabShouldShow() {
625 if ((profile != null) && profile.isPostingPermitted() && !drawer.isOpen())
630 public void fabHide() {
633 public void onAccountSummaryRowViewClicked(View view) {
635 switch (view.getId()) {
636 case R.id.account_expander:
637 row = (ViewGroup) view.getParent()
641 case R.id.account_expander_container:
642 case R.id.account_row_acc_name:
643 row = (ViewGroup) view.getParent()
647 row = (ViewGroup) view.getParent();
651 LedgerAccount acc = (LedgerAccount) row.getTag();
652 switch (view.getId()) {
653 case R.id.account_row_acc_name:
654 case R.id.account_expander:
655 case R.id.account_expander_container:
657 case R.id.account_row_acc_amounts:
662 public class SectionsPagerAdapter extends FragmentPagerAdapter {
664 SectionsPagerAdapter(FragmentManager fm) {
665 super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
670 public Fragment getItem(int position) {
671 debug("main", String.format(Locale.ENGLISH, "Switching to fragment %d", position));
674 // debug("flow", "Creating account summary fragment");
675 return new AccountSummaryFragment();
677 return new TransactionListFragment();
679 throw new IllegalStateException(
680 String.format("Unexpected fragment index: " + "%d", position));
685 public int getCount() {