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.Build;
29 import android.os.Bundle;
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.FragmentManager;
44 import androidx.fragment.app.FragmentPagerAdapter;
45 import androidx.lifecycle.ViewModelProvider;
46 import androidx.recyclerview.widget.LinearLayoutManager;
47 import androidx.recyclerview.widget.RecyclerView;
48 import androidx.viewpager.widget.ViewPager;
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;
77 public class MainActivity extends ProfileThemedActivity {
78 public static final String STATE_CURRENT_PAGE = "current_page";
79 public static final String BUNDLE_SAVED_STATE = "bundle_savedState";
80 public static final String STATE_ACC_FILTER = "account_filter";
81 private static final String PREF_THEME_ID = "themeId";
83 private View profileListHeadMore, profileListHeadCancel, profileListHeadAddProfile;
84 private View bTransactionListCancelDownload;
85 private SectionsPagerAdapter mSectionsPagerAdapter;
86 private ViewPager 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 ViewPager.SimpleOnPageChangeListener pageChangeListener;
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.removeOnPageChangeListener(pageChangeListener);
128 pageChangeListener = null;
132 protected void setupProfileColors() {
133 SharedPreferences prefs = getPreferences(MODE_PRIVATE);
134 int profileColor = prefs.getInt(PREF_THEME_ID, -2);
135 if (profileColor == -2)
136 profileColor = Data.retrieveCurrentThemeIdFromDb();
137 Colors.setupTheme(this, profileColor);
138 Colors.profileThemeId = profileColor;
139 storeThemeIdInPrefs(profileColor);
142 protected void onResume() {
147 protected void onCreate(Bundle savedInstanceState) {
148 Logger.debug("MainActivity", "onCreate()/entry");
149 super.onCreate(savedInstanceState);
150 Logger.debug("MainActivity", "onCreate()/after super");
151 setContentView(R.layout.activity_main);
153 mainModel = new ViewModelProvider(this).get(MainModel.class);
155 fab = findViewById(R.id.btn_add_transaction);
156 profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
157 profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
158 LinearLayout profileListHeadMoreAndCancel =
159 findViewById(R.id.nav_profile_list_head_buttons);
160 profileListHeadAddProfile = findViewById(R.id.nav_new_profile_button);
161 drawer = findViewById(R.id.drawer_layout);
162 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
163 mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
164 mViewPager = findViewById(R.id.root_frame);
166 Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
167 if (extra != null && savedInstanceState == null)
168 savedInstanceState = extra;
171 mToolbar = findViewById(R.id.toolbar);
172 setSupportActionBar(mToolbar);
174 Data.observeProfile(this, this::onProfileChanged);
176 Data.profiles.observe(this, this::onProfileListChanged);
177 Data.backgroundTaskProgress.observe(this, this::onRetrieveProgress);
178 Data.backgroundTasksRunning.observe(this, this::onRetrieveRunningChanged);
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 mainModel.getAccountFilter()
233 .setValue(savedInstanceState.getString(STATE_ACC_FILTER, null));
236 findViewById(R.id.btn_no_profiles_add).setOnClickListener(
237 v -> startEditProfileActivity(null));
239 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
241 findViewById(R.id.nav_new_profile_button).setOnClickListener(
242 v -> startEditProfileActivity(null));
244 RecyclerView root = findViewById(R.id.nav_profile_list);
246 throw new RuntimeException("Can't get hold on the transaction value view");
248 if (mProfileListAdapter == null)
249 mProfileListAdapter = new ProfilesRecyclerViewAdapter();
250 root.setAdapter(mProfileListAdapter);
252 mProfileListAdapter.editingProfiles.observe(this, newValue -> {
254 profileListHeadMore.setVisibility(View.GONE);
255 profileListHeadCancel.setVisibility(View.VISIBLE);
256 profileListHeadAddProfile.setVisibility(View.VISIBLE);
257 if (drawer.isDrawerOpen(GravityCompat.START)) {
258 profileListHeadMore.startAnimation(
259 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
260 profileListHeadCancel.startAnimation(
261 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
262 profileListHeadAddProfile.startAnimation(
263 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
267 profileListHeadCancel.setVisibility(View.GONE);
268 profileListHeadMore.setVisibility(View.VISIBLE);
269 profileListHeadAddProfile.setVisibility(View.GONE);
270 if (drawer.isDrawerOpen(GravityCompat.START)) {
271 profileListHeadCancel.startAnimation(
272 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
273 profileListHeadMore.startAnimation(
274 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
275 profileListHeadAddProfile.startAnimation(
276 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
280 mProfileListAdapter.notifyDataSetChanged();
283 LinearLayoutManager llm = new LinearLayoutManager(this);
285 llm.setOrientation(RecyclerView.VERTICAL);
286 root.setLayoutManager(llm);
288 profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
289 profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
290 profileListHeadMoreAndCancel.setOnClickListener(
291 (v) -> mProfileListAdapter.flipEditingProfiles());
292 if (drawerListener == null) {
293 drawerListener = new DrawerLayout.SimpleDrawerListener() {
295 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
296 if (slideOffset > 0.2)
300 public void onDrawerClosed(View drawerView) {
301 super.onDrawerClosed(drawerView);
302 mProfileListAdapter.setAnimationsEnabled(false);
303 mProfileListAdapter.editingProfiles.setValue(false);
304 Data.drawerOpen.setValue(false);
308 public void onDrawerOpened(View drawerView) {
309 super.onDrawerOpened(drawerView);
310 mProfileListAdapter.setAnimationsEnabled(true);
311 Data.drawerOpen.setValue(true);
315 drawer.addDrawerListener(drawerListener);
318 Data.drawerOpen.observe(this, open -> {
325 mainModel.getUpdateError()
326 .observe(this, (error) -> {
330 Snackbar.make(mViewPager, error, Snackbar.LENGTH_LONG)
332 mainModel.clearUpdateError();
335 private void scheduleDataRetrievalIfStale(long lastUpdate) {
336 long now = new Date().getTime();
337 if ((lastUpdate == 0) || (now > (lastUpdate + (24 * 3600 * 1000)))) {
339 Logger.debug("db::", "WEB data never fetched. scheduling a fetch");
341 Logger.debug("db", String.format(Locale.ENGLISH,
342 "WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
343 lastUpdate / 1000f, now / 1000f));
345 mainModel.scheduleTransactionListRetrieval();
348 private void createShortcuts(List<MobileLedgerProfile> list) {
349 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
352 ShortcutManager sm = getSystemService(ShortcutManager.class);
353 List<ShortcutInfo> shortcuts = new ArrayList<>();
355 for (MobileLedgerProfile p : list) {
356 if (shortcuts.size() >= sm.getMaxShortcutCountPerActivity())
359 if (!p.isPostingPermitted())
362 final ShortcutInfo.Builder builder =
363 new ShortcutInfo.Builder(this, "new_transaction_" + p.getUuid());
364 ShortcutInfo si = builder.setShortLabel(p.getName())
365 .setIcon(Icon.createWithResource(this,
366 R.drawable.thick_plus_icon))
367 .setIntent(new Intent(Intent.ACTION_VIEW, null, this,
368 NewTransactionActivity.class).putExtra("profile_uuid",
375 sm.setDynamicShortcuts(shortcuts);
377 private void onProfileListChanged(List<MobileLedgerProfile> newList) {
378 if ((newList == null) || newList.isEmpty()) {
379 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
380 findViewById(R.id.main_app_layout).setVisibility(View.GONE);
384 findViewById(R.id.main_app_layout).setVisibility(View.VISIBLE);
385 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
387 findViewById(R.id.nav_profile_list).setMinimumHeight(
388 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
390 Logger.debug("profiles", "profile list changed");
391 mProfileListAdapter.notifyDataSetChanged();
393 createShortcuts(newList);
396 * called when the current profile has changed
398 private void onProfileChanged(MobileLedgerProfile profile) {
399 if (this.profile == null) {
404 if (this.profile.equals(profile))
408 boolean haveProfile = profile != null;
411 setTitle(profile.getName());
413 setTitle(R.string.app_name);
415 mainModel.setProfile(profile);
417 this.profile = profile;
419 int newProfileTheme = haveProfile ? profile.getThemeHue() : -1;
420 if (newProfileTheme != Colors.profileThemeId) {
421 Logger.debug("profiles",
422 String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
424 Colors.profileThemeId = newProfileTheme;
425 profileThemeChanged();
426 // profileThemeChanged would restart the activity, so no need to reload the
431 findViewById(R.id.no_profiles_layout).setVisibility(haveProfile ? View.GONE : View.VISIBLE);
432 findViewById(R.id.pager_layout).setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
434 mProfileListAdapter.notifyDataSetChanged();
436 mainModel.clearTransactions();
439 mainModel.scheduleAccountListReload();
440 Logger.debug("transactions", "requesting list reload");
441 mainModel.scheduleTransactionListReload();
443 if (profile.isPostingPermitted()) {
444 mToolbar.setSubtitle(null);
448 mToolbar.setSubtitle(R.string.profile_subtitle_read_only);
453 mToolbar.setSubtitle(null);
457 updateLastUpdateTextFromDB();
459 private void profileThemeChanged() {
460 storeThemeIdInPrefs(profile.getThemeHue());
462 // un-hook all observed LiveData
463 Data.removeProfileObservers(this);
464 Data.profiles.removeObservers(this);
465 Data.lastUpdateLiveData.removeObservers(this);
469 private void storeThemeIdInPrefs(int themeId) {
470 // store the new theme id in the preferences
471 SharedPreferences prefs = getPreferences(MODE_PRIVATE);
472 SharedPreferences.Editor e = prefs.edit();
473 e.putInt(PREF_THEME_ID, themeId);
476 public void startEditProfileActivity(MobileLedgerProfile profile) {
477 Intent intent = new Intent(this, ProfileDetailActivity.class);
478 Bundle args = new Bundle();
479 if (profile != null) {
480 int index = Data.getProfileIndex(profile);
482 intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
484 intent.putExtras(args);
485 startActivity(intent, args);
487 public void fabNewTransactionClicked(View view) {
488 Intent intent = new Intent(this, NewTransactionActivity.class);
489 startActivity(intent);
490 overridePendingTransition(R.anim.slide_in_up, R.anim.dummy);
492 public void markDrawerItemCurrent(int id) {
493 TextView item = drawer.findViewById(id);
494 item.setBackgroundColor(Colors.tableRowDarkBG);
496 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
497 for (int i = 0; i < actions.getChildCount(); i++) {
498 View view = actions.getChildAt(i);
499 if (view.getId() != id) {
500 view.setBackgroundColor(Color.TRANSPARENT);
504 public void onAccountSummaryClicked(View view) {
505 drawer.closeDrawers();
507 showAccountSummaryFragment();
509 private void showAccountSummaryFragment() {
510 mViewPager.setCurrentItem(0, true);
511 mainModel.getAccountFilter()
514 public void onLatestTransactionsClicked(View view) {
515 drawer.closeDrawers();
517 showTransactionsFragment(null);
519 public void showTransactionsFragment(String accName) {
520 mainModel.getAccountFilter()
522 mViewPager.setCurrentItem(1, true);
524 public void showAccountTransactions(String accountName) {
525 mBackMeansToAccountList = true;
526 showTransactionsFragment(accountName);
529 public void onBackPressed() {
530 DrawerLayout drawer = findViewById(R.id.drawer_layout);
531 if (drawer.isDrawerOpen(GravityCompat.START)) {
532 drawer.closeDrawer(GravityCompat.START);
535 if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
536 mainModel.getAccountFilter()
538 showAccountSummaryFragment();
539 mBackMeansToAccountList = false;
542 Logger.debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
543 getSupportFragmentManager().getBackStackEntryCount()));
545 super.onBackPressed();
549 public void updateLastUpdateTextFromDB() {
553 long lastUpdate = profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
555 Logger.debug("transactions", String.format(Locale.ENGLISH, "Last update = %d", lastUpdate));
556 if (lastUpdate == 0) {
557 Data.lastUpdateLiveData.postValue(null);
560 Data.lastUpdateLiveData.postValue(new Date(lastUpdate));
563 // this is unfortunate, but it appears we need a two-stage rocket to make
564 // a value reach a recycler view item holder. first stage is a regular
565 // LiveData that can be observed by an activity (this).
566 // the second stage forwards the changes, in the UI thread, to the
567 // observable value, observed by the view holders.
568 // view holders can't observe the LiveData because they don't have
569 // access to lifecycle owners. oh, also the value is updated by a thread
570 // so it must be tunnelled by an activity for it to reach the view
571 // holders in the UI thread
572 Data.lastUpdateLiveData.observe(this, date -> runOnUiThread(
573 () -> Data.lastUpdate.set((date == null) ? 0 : date.getTime())));
574 scheduleDataRetrievalIfStale(lastUpdate);
577 public void onStopTransactionRefreshClick(View view) {
578 Logger.debug("interactive", "Cancelling transactions refresh");
579 mainModel.stopTransactionsRetrieval();
580 bTransactionListCancelDownload.setEnabled(false);
582 public void onRetrieveRunningChanged(Boolean running) {
583 final View progressLayout = findViewById(R.id.transaction_progress_layout);
585 ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
586 bTransactionListCancelDownload.setEnabled(true);
587 ColorStateList csl = Colors.getColorStateList();
588 progressBar.setIndeterminateTintList(csl);
589 progressBar.setProgressTintList(csl);
590 progressBar.setIndeterminate(true);
591 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
592 progressBar.setProgress(0, false);
595 progressBar.setProgress(0);
597 progressLayout.setVisibility(View.VISIBLE);
600 progressLayout.setVisibility(View.GONE);
603 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
604 ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
606 if (progress.getState() == RetrieveTransactionsTask.ProgressState.FINISHED) {
607 Logger.debug("progress", "Done");
608 findViewById(R.id.transaction_progress_layout).setVisibility(View.GONE);
610 mainModel.transactionRetrievalDone();
612 if (progress.getError() != null) {
613 Snackbar.make(mViewPager, progress.getError(), Snackbar.LENGTH_LONG)
622 bTransactionListCancelDownload.setEnabled(true);
623 // ColorStateList csl = Colors.getColorStateList();
624 // progressBar.setIndeterminateTintList(csl);
625 // progressBar.setProgressTintList(csl);
626 // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
627 // progressBar.setProgress(0, false);
629 // progressBar.setProgress(0);
630 findViewById(R.id.transaction_progress_layout).setVisibility(View.VISIBLE);
632 if (progress.isIndeterminate() || (progress.getTotal() <= 0)) {
633 progressBar.setIndeterminate(true);
634 Logger.debug("progress", "indeterminate");
637 if (progressBar.isIndeterminate()) {
638 progressBar.setIndeterminate(false);
640 // Logger.debug("progress",
641 // String.format(Locale.US, "%d/%d", progress.getProgress(), progress.getTotal
643 progressBar.setMax(progress.getTotal());
644 // for some reason animation doesn't work - no progress is shown (stick at 0)
645 // on lineageOS 14.1 (Nougat, 7.1.2)
646 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
647 progressBar.setProgress(progress.getProgress(), false);
649 progressBar.setProgress(progress.getProgress());
652 public void fabShouldShow() {
653 if ((profile != null) && profile.isPostingPermitted() && !drawer.isOpen())
658 public void fabHide() {
662 public static class SectionsPagerAdapter extends FragmentPagerAdapter {
664 SectionsPagerAdapter(FragmentManager fm) {
665 super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
670 public Fragment getItem(int position) {
672 String.format(Locale.ENGLISH, "Switching to fragment %d", position));
675 // debug("flow", "Creating account summary fragment");
676 return new AccountSummaryFragment();
678 return new TransactionListFragment();
680 throw new IllegalStateException(
681 String.format("Unexpected fragment index: " + "%d", position));
686 public int getCount() {