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.pm.PackageInfo;
22 import android.content.pm.ShortcutInfo;
23 import android.content.pm.ShortcutManager;
24 import android.content.res.ColorStateList;
25 import android.graphics.Color;
26 import android.graphics.drawable.Icon;
27 import android.os.Build;
28 import android.os.Bundle;
29 import android.text.format.DateUtils;
30 import android.util.Log;
31 import android.view.View;
32 import android.view.animation.AnimationUtils;
33 import android.widget.LinearLayout;
34 import android.widget.ProgressBar;
35 import android.widget.TextView;
37 import androidx.annotation.NonNull;
38 import androidx.appcompat.app.ActionBarDrawerToggle;
39 import androidx.appcompat.widget.Toolbar;
40 import androidx.core.view.GravityCompat;
41 import androidx.drawerlayout.widget.DrawerLayout;
42 import androidx.fragment.app.Fragment;
43 import androidx.fragment.app.FragmentActivity;
44 import androidx.lifecycle.ViewModelProvider;
45 import androidx.recyclerview.widget.LinearLayoutManager;
46 import androidx.recyclerview.widget.RecyclerView;
47 import androidx.viewpager2.adapter.FragmentStateAdapter;
48 import androidx.viewpager2.widget.ViewPager2;
50 import com.google.android.material.floatingactionbutton.FloatingActionButton;
51 import com.google.android.material.snackbar.Snackbar;
53 import net.ktnx.mobileledger.R;
54 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
55 import net.ktnx.mobileledger.model.Data;
56 import net.ktnx.mobileledger.model.MobileLedgerProfile;
57 import net.ktnx.mobileledger.ui.MainModel;
58 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
59 import net.ktnx.mobileledger.ui.profiles.ProfileDetailFragment;
60 import net.ktnx.mobileledger.ui.profiles.ProfilesRecyclerViewAdapter;
61 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
62 import net.ktnx.mobileledger.utils.Colors;
63 import net.ktnx.mobileledger.utils.Logger;
64 import net.ktnx.mobileledger.utils.MLDB;
66 import org.jetbrains.annotations.NotNull;
68 import java.util.ArrayList;
69 import java.util.Date;
70 import java.util.List;
71 import java.util.Locale;
72 import java.util.Objects;
78 public class MainActivity extends ProfileThemedActivity {
79 public static final String STATE_CURRENT_PAGE = "current_page";
80 public static final String BUNDLE_SAVED_STATE = "bundle_savedState";
81 public static final String STATE_ACC_FILTER = "account_filter";
83 private View profileListHeadMore, profileListHeadCancel, profileListHeadAddProfile;
84 private View bTransactionListCancelDownload;
85 private SectionsPagerAdapter mSectionsPagerAdapter;
86 private ViewPager2 mViewPager;
87 private FloatingActionButton fab;
88 private ProfilesRecyclerViewAdapter mProfileListAdapter;
89 private int mCurrentPage;
90 private boolean mBackMeansToAccountList = false;
91 private Toolbar mToolbar;
92 private DrawerLayout.SimpleDrawerListener drawerListener;
93 private ActionBarDrawerToggle barDrawerToggle;
94 private ViewPager2.OnPageChangeCallback pageChangeCallback;
95 private MobileLedgerProfile profile;
96 private MainModel mainModel;
98 protected void onStart() {
101 Logger.debug("MainActivity", "onStart()");
103 mViewPager.setCurrentItem(mCurrentPage, false);
106 protected void onSaveInstanceState(@NotNull Bundle outState) {
107 super.onSaveInstanceState(outState);
108 outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
109 if (mainModel.getAccountFilter()
111 outState.putString(STATE_ACC_FILTER, mainModel.getAccountFilter()
115 protected void onDestroy() {
116 mSectionsPagerAdapter = null;
117 RecyclerView root = findViewById(R.id.nav_profile_list);
119 root.setAdapter(null);
121 drawer.removeDrawerListener(drawerListener);
122 drawerListener = null;
124 drawer.removeDrawerListener(barDrawerToggle);
125 barDrawerToggle = null;
126 if (mViewPager != null)
127 mViewPager.unregisterOnPageChangeCallback(pageChangeCallback);
128 pageChangeCallback = null;
132 protected void setupProfileColors() {
133 final int profileColor = Data.retrieveCurrentThemeIdFromDb();
134 Colors.setupTheme(this, profileColor);
135 Colors.profileThemeId = profileColor;
138 protected void onResume() {
143 protected void onCreate(Bundle savedInstanceState) {
144 Logger.debug("MainActivity", "onCreate()/entry");
145 super.onCreate(savedInstanceState);
146 Logger.debug("MainActivity", "onCreate()/after super");
147 setContentView(R.layout.activity_main);
149 mainModel = new ViewModelProvider(this).get(MainModel.class);
151 fab = findViewById(R.id.btn_add_transaction);
152 profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
153 profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
154 LinearLayout profileListHeadMoreAndCancel =
155 findViewById(R.id.nav_profile_list_head_buttons);
156 profileListHeadAddProfile = findViewById(R.id.nav_new_profile_button);
157 drawer = findViewById(R.id.drawer_layout);
158 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
159 mSectionsPagerAdapter = new SectionsPagerAdapter(this);
160 mViewPager = findViewById(R.id.root_frame);
162 Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
163 if (extra != null && savedInstanceState == null)
164 savedInstanceState = extra;
167 mToolbar = findViewById(R.id.toolbar);
168 setSupportActionBar(mToolbar);
170 Data.observeProfile(this, this::onProfileChanged);
172 Data.profiles.observe(this, this::onProfileListChanged);
173 Data.backgroundTaskProgress.observe(this, this::onRetrieveProgress);
174 Data.backgroundTasksRunning.observe(this, this::onRetrieveRunningChanged);
176 if (barDrawerToggle == null) {
177 barDrawerToggle = new ActionBarDrawerToggle(this, drawer, mToolbar,
178 R.string.navigation_drawer_open, R.string.navigation_drawer_close);
179 drawer.addDrawerListener(barDrawerToggle);
181 barDrawerToggle.syncState();
184 PackageInfo pi = getApplicationContext().getPackageManager()
185 .getPackageInfo(getPackageName(), 0);
186 ((TextView) findViewById(R.id.nav_upper).findViewById(
187 R.id.drawer_version_text)).setText(pi.versionName);
188 ((TextView) findViewById(R.id.no_profiles_layout).findViewById(
189 R.id.drawer_version_text)).setText(pi.versionName);
191 catch (Exception e) {
195 markDrawerItemCurrent(R.id.nav_account_summary);
197 mViewPager.setAdapter(mSectionsPagerAdapter);
199 if (pageChangeCallback == null) {
200 pageChangeCallback = new ViewPager2.OnPageChangeCallback() {
202 public void onPageSelected(int position) {
203 mCurrentPage = position;
206 markDrawerItemCurrent(R.id.nav_account_summary);
209 markDrawerItemCurrent(R.id.nav_latest_transactions);
212 Log.e("MainActivity",
213 String.format("Unexpected page index %d", position));
216 super.onPageSelected(position);
219 mViewPager.registerOnPageChangeCallback(pageChangeCallback);
223 if (savedInstanceState != null) {
224 int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
225 if (currentPage != -1) {
226 mCurrentPage = currentPage;
228 mainModel.getAccountFilter()
229 .setValue(savedInstanceState.getString(STATE_ACC_FILTER, null));
232 findViewById(R.id.btn_no_profiles_add).setOnClickListener(
233 v -> startEditProfileActivity(null));
235 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
237 findViewById(R.id.nav_new_profile_button).setOnClickListener(
238 v -> startEditProfileActivity(null));
240 findViewById(R.id.transaction_list_cancel_download).setOnClickListener(this::onStopTransactionRefreshClick);
242 RecyclerView root = findViewById(R.id.nav_profile_list);
244 throw new RuntimeException("Can't get hold on the transaction value view");
246 if (mProfileListAdapter == null)
247 mProfileListAdapter = new ProfilesRecyclerViewAdapter();
248 root.setAdapter(mProfileListAdapter);
250 mProfileListAdapter.editingProfiles.observe(this, newValue -> {
252 profileListHeadMore.setVisibility(View.GONE);
253 profileListHeadCancel.setVisibility(View.VISIBLE);
254 profileListHeadAddProfile.setVisibility(View.VISIBLE);
255 if (drawer.isDrawerOpen(GravityCompat.START)) {
256 profileListHeadMore.startAnimation(
257 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
258 profileListHeadCancel.startAnimation(
259 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
260 profileListHeadAddProfile.startAnimation(
261 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
265 profileListHeadCancel.setVisibility(View.GONE);
266 profileListHeadMore.setVisibility(View.VISIBLE);
267 profileListHeadAddProfile.setVisibility(View.GONE);
268 if (drawer.isDrawerOpen(GravityCompat.START)) {
269 profileListHeadCancel.startAnimation(
270 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
271 profileListHeadMore.startAnimation(
272 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
273 profileListHeadAddProfile.startAnimation(
274 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
278 mProfileListAdapter.notifyDataSetChanged();
281 LinearLayoutManager llm = new LinearLayoutManager(this);
283 llm.setOrientation(RecyclerView.VERTICAL);
284 root.setLayoutManager(llm);
286 profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
287 profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
288 profileListHeadMoreAndCancel.setOnClickListener(
289 (v) -> mProfileListAdapter.flipEditingProfiles());
290 if (drawerListener == null) {
291 drawerListener = new DrawerLayout.SimpleDrawerListener() {
293 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
294 if (slideOffset > 0.2)
298 public void onDrawerClosed(View drawerView) {
299 super.onDrawerClosed(drawerView);
300 mProfileListAdapter.setAnimationsEnabled(false);
301 mProfileListAdapter.editingProfiles.setValue(false);
302 Data.drawerOpen.setValue(false);
306 public void onDrawerOpened(View drawerView) {
307 super.onDrawerOpened(drawerView);
308 mProfileListAdapter.setAnimationsEnabled(true);
309 Data.drawerOpen.setValue(true);
313 drawer.addDrawerListener(drawerListener);
316 Data.drawerOpen.observe(this, open -> {
323 mainModel.getUpdateError()
324 .observe(this, (error) -> {
328 Snackbar.make(mViewPager, error, Snackbar.LENGTH_LONG)
330 mainModel.clearUpdateError();
332 Data.locale.observe(this, l -> refreshLastUpdateInfo());
333 Data.lastUpdateDate.observe(this, date -> refreshLastUpdateInfo());
334 Data.lastUpdateTransactionCount.observe(this, date -> refreshLastUpdateInfo());
335 Data.lastUpdateAccountCount.observe(this, date -> refreshLastUpdateInfo());
337 private void scheduleDataRetrievalIfStale(long lastUpdate) {
338 long now = new Date().getTime();
339 if ((lastUpdate == 0) || (now > (lastUpdate + (24 * 3600 * 1000)))) {
341 Logger.debug("db::", "WEB data never fetched. scheduling a fetch");
343 Logger.debug("db", String.format(Locale.ENGLISH,
344 "WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
345 lastUpdate / 1000f, now / 1000f));
347 mainModel.scheduleTransactionListRetrieval();
350 private void createShortcuts(List<MobileLedgerProfile> list) {
351 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
354 ShortcutManager sm = getSystemService(ShortcutManager.class);
355 List<ShortcutInfo> shortcuts = new ArrayList<>();
357 for (MobileLedgerProfile p : list) {
358 if (shortcuts.size() >= sm.getMaxShortcutCountPerActivity())
361 if (!p.isPostingPermitted())
364 final ShortcutInfo.Builder builder =
365 new ShortcutInfo.Builder(this, "new_transaction_" + p.getUuid());
366 ShortcutInfo si = builder.setShortLabel(p.getName())
367 .setIcon(Icon.createWithResource(this,
368 R.drawable.thick_plus_icon))
369 .setIntent(new Intent(Intent.ACTION_VIEW, null, this,
370 NewTransactionActivity.class).putExtra("profile_uuid",
377 sm.setDynamicShortcuts(shortcuts);
379 private void onProfileListChanged(List<MobileLedgerProfile> newList) {
380 if ((newList == null) || newList.isEmpty()) {
381 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
382 findViewById(R.id.main_app_layout).setVisibility(View.GONE);
386 findViewById(R.id.main_app_layout).setVisibility(View.VISIBLE);
387 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
389 findViewById(R.id.nav_profile_list).setMinimumHeight(
390 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
392 Logger.debug("profiles", "profile list changed");
393 mProfileListAdapter.notifyDataSetChanged();
395 createShortcuts(newList);
398 * called when the current profile has changed
400 private void onProfileChanged(MobileLedgerProfile profile) {
401 if (this.profile == null) {
406 if (this.profile.equals(profile))
410 boolean haveProfile = profile != null;
413 setTitle(profile.getName());
415 setTitle(R.string.app_name);
417 mainModel.setProfile(profile);
419 this.profile = profile;
421 int newProfileTheme = haveProfile ? profile.getThemeHue() : -1;
422 if (newProfileTheme != Colors.profileThemeId) {
423 Logger.debug("profiles",
424 String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
426 Colors.profileThemeId = newProfileTheme;
427 profileThemeChanged();
428 // profileThemeChanged would restart the activity, so no need to reload the
433 findViewById(R.id.no_profiles_layout).setVisibility(haveProfile ? View.GONE : View.VISIBLE);
434 findViewById(R.id.pager_layout).setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
436 mProfileListAdapter.notifyDataSetChanged();
438 mainModel.clearAccounts();
439 mainModel.clearTransactions();
442 mainModel.scheduleAccountListReload();
443 Logger.debug("transactions", "requesting list reload");
444 mainModel.scheduleTransactionListReload();
446 if (profile.isPostingPermitted()) {
447 mToolbar.setSubtitle(null);
451 mToolbar.setSubtitle(R.string.profile_subtitle_read_only);
456 mToolbar.setSubtitle(null);
460 updateLastUpdateTextFromDB();
462 private void profileThemeChanged() {
463 // un-hook all observed LiveData
464 Data.removeProfileObservers(this);
465 Data.profiles.removeObservers(this);
466 Data.lastUpdateTransactionCount.removeObservers(this);
467 Data.lastUpdateAccountCount.removeObservers(this);
468 Data.lastUpdateDate.removeObservers(this);
472 public void startEditProfileActivity(MobileLedgerProfile profile) {
473 Intent intent = new Intent(this, ProfileDetailActivity.class);
474 Bundle args = new Bundle();
475 if (profile != null) {
476 int index = Data.getProfileIndex(profile);
478 intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
480 intent.putExtras(args);
481 startActivity(intent, args);
483 public void fabNewTransactionClicked(View view) {
484 Intent intent = new Intent(this, NewTransactionActivity.class);
485 startActivity(intent);
486 overridePendingTransition(R.anim.slide_in_up, R.anim.dummy);
488 public void markDrawerItemCurrent(int id) {
489 TextView item = drawer.findViewById(id);
490 item.setBackgroundColor(Colors.tableRowDarkBG);
492 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
493 for (int i = 0; i < actions.getChildCount(); i++) {
494 View view = actions.getChildAt(i);
495 if (view.getId() != id) {
496 view.setBackgroundColor(Color.TRANSPARENT);
500 public void onAccountSummaryClicked(View view) {
501 drawer.closeDrawers();
503 showAccountSummaryFragment();
505 private void showAccountSummaryFragment() {
506 mViewPager.setCurrentItem(0, true);
507 mainModel.getAccountFilter()
510 public void onLatestTransactionsClicked(View view) {
511 drawer.closeDrawers();
513 showTransactionsFragment(null);
515 public void showTransactionsFragment(String accName) {
516 mainModel.getAccountFilter()
518 mViewPager.setCurrentItem(1, true);
520 public void showAccountTransactions(String accountName) {
521 mBackMeansToAccountList = true;
522 showTransactionsFragment(accountName);
525 public void onBackPressed() {
526 DrawerLayout drawer = findViewById(R.id.drawer_layout);
527 if (drawer.isDrawerOpen(GravityCompat.START)) {
528 drawer.closeDrawer(GravityCompat.START);
531 if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
532 mainModel.getAccountFilter()
534 showAccountSummaryFragment();
535 mBackMeansToAccountList = false;
538 Logger.debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
539 getSupportFragmentManager().getBackStackEntryCount()));
541 super.onBackPressed();
545 public void updateLastUpdateTextFromDB() {
549 long lastUpdate = profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
551 Logger.debug("transactions", String.format(Locale.ENGLISH, "Last update = %d", lastUpdate));
552 if (lastUpdate == 0) {
553 Data.lastUpdateDate.postValue(null);
556 Data.lastUpdateDate.postValue(new Date(lastUpdate));
559 scheduleDataRetrievalIfStale(lastUpdate);
562 private void refreshLastUpdateInfo() {
563 final int formatFlags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR |
564 DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_NUMERIC_DATE;
565 String templateForTransactions =
566 getResources().getString(R.string.transaction_count_summary);
567 String templateForAccounts = getResources().getString(R.string.account_count_summary);
568 Integer accountCount = Data.lastUpdateAccountCount.getValue();
569 Integer transactionCount = Data.lastUpdateTransactionCount.getValue();
570 Date lastUpdate = Data.lastUpdateDate.getValue();
571 if (lastUpdate == null) {
572 Data.lastTransactionsUpdateText.set("----");
573 Data.lastAccountsUpdateText.set("----");
576 Data.lastTransactionsUpdateText.set(
577 String.format(Objects.requireNonNull(Data.locale.getValue()),
578 templateForTransactions,
579 transactionCount == null ? 0 : transactionCount,
580 DateUtils.formatDateTime(this, lastUpdate.getTime(), formatFlags)));
581 Data.lastAccountsUpdateText.set(
582 String.format(Objects.requireNonNull(Data.locale.getValue()),
583 templateForAccounts, accountCount == null ? 0 : accountCount,
584 DateUtils.formatDateTime(this, lastUpdate.getTime(), formatFlags)));
587 public void onStopTransactionRefreshClick(View view) {
588 Logger.debug("interactive", "Cancelling transactions refresh");
589 mainModel.stopTransactionsRetrieval();
590 bTransactionListCancelDownload.setEnabled(false);
592 public void onRetrieveRunningChanged(Boolean running) {
593 final View progressLayout = findViewById(R.id.transaction_progress_layout);
595 ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
596 bTransactionListCancelDownload.setEnabled(true);
597 ColorStateList csl = Colors.getColorStateList();
598 progressBar.setIndeterminateTintList(csl);
599 progressBar.setProgressTintList(csl);
600 progressBar.setIndeterminate(true);
601 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
602 progressBar.setProgress(0, false);
605 progressBar.setProgress(0);
607 progressLayout.setVisibility(View.VISIBLE);
610 progressLayout.setVisibility(View.GONE);
613 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
614 ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
616 if (progress.getState() == RetrieveTransactionsTask.ProgressState.FINISHED) {
617 Logger.debug("progress", "Done");
618 findViewById(R.id.transaction_progress_layout).setVisibility(View.GONE);
620 mainModel.transactionRetrievalDone();
622 if (progress.getError() != null) {
623 Snackbar.make(mViewPager, progress.getError(), Snackbar.LENGTH_LONG)
632 bTransactionListCancelDownload.setEnabled(true);
633 // ColorStateList csl = Colors.getColorStateList();
634 // progressBar.setIndeterminateTintList(csl);
635 // progressBar.setProgressTintList(csl);
636 // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
637 // progressBar.setProgress(0, false);
639 // progressBar.setProgress(0);
640 findViewById(R.id.transaction_progress_layout).setVisibility(View.VISIBLE);
642 if (progress.isIndeterminate() || (progress.getTotal() <= 0)) {
643 progressBar.setIndeterminate(true);
644 Logger.debug("progress", "indeterminate");
647 if (progressBar.isIndeterminate()) {
648 progressBar.setIndeterminate(false);
650 // Logger.debug("progress",
651 // String.format(Locale.US, "%d/%d", progress.getProgress(), progress.getTotal
653 progressBar.setMax(progress.getTotal());
654 // for some reason animation doesn't work - no progress is shown (stick at 0)
655 // on lineageOS 14.1 (Nougat, 7.1.2)
656 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
657 progressBar.setProgress(progress.getProgress(), false);
659 progressBar.setProgress(progress.getProgress());
662 public void fabShouldShow() {
663 if ((profile != null) && profile.isPostingPermitted() && !drawer.isOpen())
668 public void fabHide() {
672 public static class SectionsPagerAdapter extends FragmentStateAdapter {
674 public SectionsPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
675 super(fragmentActivity);
679 public Fragment createFragment(int position) {
681 String.format(Locale.ENGLISH, "Switching to fragment %d", position));
684 // debug("flow", "Creating account summary fragment");
685 return new AccountSummaryFragment();
687 return new TransactionListFragment();
689 throw new IllegalStateException(
690 String.format("Unexpected fragment index: " + "%d", position));
695 public int getItemCount() {