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.text.DateFormat;
69 import java.util.ArrayList;
70 import java.util.Date;
71 import java.util.List;
72 import java.util.Locale;
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";
82 private static final String PREF_THEME_ID = "themeId";
84 private View profileListHeadMore, profileListHeadCancel, profileListHeadAddProfile;
85 private View bTransactionListCancelDownload;
86 private SectionsPagerAdapter mSectionsPagerAdapter;
87 private ViewPager mViewPager;
88 private FloatingActionButton fab;
89 private ProfilesRecyclerViewAdapter mProfileListAdapter;
90 private int mCurrentPage;
91 private boolean mBackMeansToAccountList = false;
92 private Toolbar mToolbar;
93 private DrawerLayout.SimpleDrawerListener drawerListener;
94 private ActionBarDrawerToggle barDrawerToggle;
95 private ViewPager.SimpleOnPageChangeListener pageChangeListener;
96 private MobileLedgerProfile profile;
97 private MainModel mainModel;
99 protected void onStart() {
102 Logger.debug("MainActivity", "onStart()");
104 mViewPager.setCurrentItem(mCurrentPage, false);
107 protected void onSaveInstanceState(@NotNull Bundle outState) {
108 super.onSaveInstanceState(outState);
109 outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
110 if (mainModel.getAccountFilter()
112 outState.putString(STATE_ACC_FILTER, mainModel.getAccountFilter()
116 protected void onDestroy() {
117 mSectionsPagerAdapter = null;
118 RecyclerView root = findViewById(R.id.nav_profile_list);
120 root.setAdapter(null);
122 drawer.removeDrawerListener(drawerListener);
123 drawerListener = null;
125 drawer.removeDrawerListener(barDrawerToggle);
126 barDrawerToggle = null;
127 if (mViewPager != null)
128 mViewPager.removeOnPageChangeListener(pageChangeListener);
129 pageChangeListener = null;
133 protected void setupProfileColors() {
134 SharedPreferences prefs = getPreferences(MODE_PRIVATE);
135 int profileColor = prefs.getInt(PREF_THEME_ID, -2);
136 if (profileColor == -2)
137 profileColor = Data.retrieveCurrentThemeIdFromDb();
138 Colors.setupTheme(this, profileColor);
139 Colors.profileThemeId = profileColor;
140 storeThemeIdInPrefs(profileColor);
143 protected void onResume() {
148 protected void onCreate(Bundle savedInstanceState) {
149 Logger.debug("MainActivity", "onCreate()/entry");
150 super.onCreate(savedInstanceState);
151 Logger.debug("MainActivity", "onCreate()/after super");
152 setContentView(R.layout.activity_main);
154 mainModel = new ViewModelProvider(this).get(MainModel.class);
156 fab = findViewById(R.id.btn_add_transaction);
157 profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
158 profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
159 LinearLayout profileListHeadMoreAndCancel =
160 findViewById(R.id.nav_profile_list_head_buttons);
161 profileListHeadAddProfile = findViewById(R.id.nav_new_profile_button);
162 drawer = findViewById(R.id.drawer_layout);
163 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
164 mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
165 mViewPager = findViewById(R.id.root_frame);
167 Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
168 if (extra != null && savedInstanceState == null)
169 savedInstanceState = extra;
172 mToolbar = findViewById(R.id.toolbar);
173 setSupportActionBar(mToolbar);
175 Data.observeProfile(this, this::onProfileChanged);
177 Data.profiles.observe(this, this::onProfileListChanged);
178 Data.backgroundTaskProgress.observe(this, this::onRetrieveProgress);
179 Data.backgroundTasksRunning.observe(this, this::onRetrieveRunningChanged);
181 if (barDrawerToggle == null) {
182 barDrawerToggle = new ActionBarDrawerToggle(this, drawer, mToolbar,
183 R.string.navigation_drawer_open, R.string.navigation_drawer_close);
184 drawer.addDrawerListener(barDrawerToggle);
186 barDrawerToggle.syncState();
189 PackageInfo pi = getApplicationContext().getPackageManager()
190 .getPackageInfo(getPackageName(), 0);
191 ((TextView) findViewById(R.id.nav_upper).findViewById(
192 R.id.drawer_version_text)).setText(pi.versionName);
193 ((TextView) findViewById(R.id.no_profiles_layout).findViewById(
194 R.id.drawer_version_text)).setText(pi.versionName);
196 catch (Exception e) {
200 markDrawerItemCurrent(R.id.nav_account_summary);
202 mViewPager.setAdapter(mSectionsPagerAdapter);
204 if (pageChangeListener == null) {
205 pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
207 public void onPageSelected(int position) {
208 mCurrentPage = position;
211 markDrawerItemCurrent(R.id.nav_account_summary);
214 markDrawerItemCurrent(R.id.nav_latest_transactions);
217 Log.e("MainActivity",
218 String.format("Unexpected page index %d", position));
221 super.onPageSelected(position);
224 mViewPager.addOnPageChangeListener(pageChangeListener);
228 if (savedInstanceState != null) {
229 int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
230 if (currentPage != -1) {
231 mCurrentPage = currentPage;
233 mainModel.getAccountFilter()
234 .setValue(savedInstanceState.getString(STATE_ACC_FILTER, null));
237 mainModel.lastUpdateDate.observe(this, this::updateLastUpdateDisplay);
239 findViewById(R.id.btn_no_profiles_add).setOnClickListener(
240 v -> startEditProfileActivity(null));
242 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
244 findViewById(R.id.nav_new_profile_button).setOnClickListener(
245 v -> startEditProfileActivity(null));
247 RecyclerView root = findViewById(R.id.nav_profile_list);
249 throw new RuntimeException("Can't get hold on the transaction value view");
251 if (mProfileListAdapter == null)
252 mProfileListAdapter = new ProfilesRecyclerViewAdapter();
253 root.setAdapter(mProfileListAdapter);
255 mProfileListAdapter.editingProfiles.observe(this, newValue -> {
257 profileListHeadMore.setVisibility(View.GONE);
258 profileListHeadCancel.setVisibility(View.VISIBLE);
259 profileListHeadAddProfile.setVisibility(View.VISIBLE);
260 if (drawer.isDrawerOpen(GravityCompat.START)) {
261 profileListHeadMore.startAnimation(
262 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
263 profileListHeadCancel.startAnimation(
264 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
265 profileListHeadAddProfile.startAnimation(
266 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
270 profileListHeadCancel.setVisibility(View.GONE);
271 profileListHeadMore.setVisibility(View.VISIBLE);
272 profileListHeadAddProfile.setVisibility(View.GONE);
273 if (drawer.isDrawerOpen(GravityCompat.START)) {
274 profileListHeadCancel.startAnimation(
275 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
276 profileListHeadMore.startAnimation(
277 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
278 profileListHeadAddProfile.startAnimation(
279 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
283 mProfileListAdapter.notifyDataSetChanged();
286 LinearLayoutManager llm = new LinearLayoutManager(this);
288 llm.setOrientation(RecyclerView.VERTICAL);
289 root.setLayoutManager(llm);
291 profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
292 profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
293 profileListHeadMoreAndCancel.setOnClickListener(
294 (v) -> mProfileListAdapter.flipEditingProfiles());
295 if (drawerListener == null) {
296 drawerListener = new DrawerLayout.SimpleDrawerListener() {
298 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
299 if (slideOffset > 0.2)
303 public void onDrawerClosed(View drawerView) {
304 super.onDrawerClosed(drawerView);
305 mProfileListAdapter.setAnimationsEnabled(false);
306 mProfileListAdapter.editingProfiles.setValue(false);
307 Data.drawerOpen.setValue(false);
311 public void onDrawerOpened(View drawerView) {
312 super.onDrawerOpened(drawerView);
313 mProfileListAdapter.setAnimationsEnabled(true);
314 Data.drawerOpen.setValue(true);
318 drawer.addDrawerListener(drawerListener);
321 Data.drawerOpen.observe(this, open -> {
328 mainModel.getUpdateError()
329 .observe(this, (error) -> {
333 Snackbar.make(mViewPager, error, Snackbar.LENGTH_LONG)
335 mainModel.clearUpdateError();
338 private void scheduleDataRetrievalIfStale(Date lastUpdate) {
339 long now = new Date().getTime();
340 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
341 if (lastUpdate == null)
342 Logger.debug("db::", "WEB data never fetched. scheduling a fetch");
344 Logger.debug("db", String.format(Locale.ENGLISH,
345 "WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
346 lastUpdate.getTime() / 1000f, now / 1000f));
348 mainModel.scheduleTransactionListRetrieval();
351 private void createShortcuts(List<MobileLedgerProfile> list) {
352 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
355 ShortcutManager sm = getSystemService(ShortcutManager.class);
356 List<ShortcutInfo> shortcuts = new ArrayList<>();
358 for (MobileLedgerProfile p : list) {
359 if (shortcuts.size() >= sm.getMaxShortcutCountPerActivity())
362 if (!p.isPostingPermitted())
365 final ShortcutInfo.Builder builder =
366 new ShortcutInfo.Builder(this, "new_transaction_" + p.getUuid());
367 ShortcutInfo si = builder.setShortLabel(p.getName())
368 .setIcon(Icon.createWithResource(this,
369 R.drawable.thick_plus_icon))
370 .setIntent(new Intent(Intent.ACTION_VIEW, null, this,
371 NewTransactionActivity.class).putExtra("profile_uuid",
378 sm.setDynamicShortcuts(shortcuts);
380 private void onProfileListChanged(List<MobileLedgerProfile> newList) {
381 if ((newList == null) || newList.isEmpty()) {
382 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
383 findViewById(R.id.main_app_layout).setVisibility(View.GONE);
387 findViewById(R.id.main_app_layout).setVisibility(View.VISIBLE);
388 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
390 findViewById(R.id.nav_profile_list).setMinimumHeight(
391 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
393 Logger.debug("profiles", "profile list changed");
394 mProfileListAdapter.notifyDataSetChanged();
396 createShortcuts(newList);
399 * called when the current profile has changed
401 private void onProfileChanged(MobileLedgerProfile profile) {
402 if (this.profile == null) {
407 if (this.profile.equals(profile))
411 boolean haveProfile = profile != null;
414 setTitle(profile.getName());
416 setTitle(R.string.app_name);
418 mainModel.setProfile(profile);
420 this.profile = profile;
422 int newProfileTheme = haveProfile ? profile.getThemeHue() : -1;
423 if (newProfileTheme != Colors.profileThemeId) {
424 Logger.debug("profiles",
425 String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
427 Colors.profileThemeId = newProfileTheme;
428 profileThemeChanged();
429 // profileThemeChanged would restart the activity, so no need to reload the
434 findViewById(R.id.no_profiles_layout).setVisibility(haveProfile ? View.GONE : View.VISIBLE);
435 findViewById(R.id.pager_layout).setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
437 mProfileListAdapter.notifyDataSetChanged();
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 updateLastUpdateDisplay(Date newValue) {
463 LinearLayout l = findViewById(R.id.transactions_last_update_layout);
464 TextView v = findViewById(R.id.transactions_last_update);
465 if (newValue == null) {
466 l.setVisibility(View.INVISIBLE);
467 Logger.debug("main", "no last update date :(");
470 final String text = DateFormat.getDateTimeInstance()
473 l.setVisibility(View.VISIBLE);
474 Logger.debug("main", String.format("Date formatted: %s", text));
477 scheduleDataRetrievalIfStale(newValue);
479 private void profileThemeChanged() {
480 storeThemeIdInPrefs(profile.getThemeHue());
482 // un-hook all observed LiveData
483 Data.removeProfileObservers(this);
484 Data.profiles.removeObservers(this);
485 mainModel.lastUpdateDate.removeObservers(this);
489 private void storeThemeIdInPrefs(int themeId) {
490 // store the new theme id in the preferences
491 SharedPreferences prefs = getPreferences(MODE_PRIVATE);
492 SharedPreferences.Editor e = prefs.edit();
493 e.putInt(PREF_THEME_ID, themeId);
496 public void startEditProfileActivity(MobileLedgerProfile profile) {
497 Intent intent = new Intent(this, ProfileDetailActivity.class);
498 Bundle args = new Bundle();
499 if (profile != null) {
500 int index = Data.getProfileIndex(profile);
502 intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
504 intent.putExtras(args);
505 startActivity(intent, args);
507 public void fabNewTransactionClicked(View view) {
508 Intent intent = new Intent(this, NewTransactionActivity.class);
509 startActivity(intent);
510 overridePendingTransition(R.anim.slide_in_up, R.anim.dummy);
512 public void markDrawerItemCurrent(int id) {
513 TextView item = drawer.findViewById(id);
514 item.setBackgroundColor(Colors.tableRowDarkBG);
516 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
517 for (int i = 0; i < actions.getChildCount(); i++) {
518 View view = actions.getChildAt(i);
519 if (view.getId() != id) {
520 view.setBackgroundColor(Color.TRANSPARENT);
524 public void onAccountSummaryClicked(View view) {
525 drawer.closeDrawers();
527 showAccountSummaryFragment();
529 private void showAccountSummaryFragment() {
530 mViewPager.setCurrentItem(0, true);
531 mainModel.getAccountFilter()
534 public void onLatestTransactionsClicked(View view) {
535 drawer.closeDrawers();
537 showTransactionsFragment(null);
539 public void showTransactionsFragment(String accName) {
540 mainModel.getAccountFilter()
542 mViewPager.setCurrentItem(1, true);
544 public void showAccountTransactions(String accountName) {
545 mBackMeansToAccountList = true;
546 showTransactionsFragment(accountName);
549 public void onBackPressed() {
550 DrawerLayout drawer = findViewById(R.id.drawer_layout);
551 if (drawer.isDrawerOpen(GravityCompat.START)) {
552 drawer.closeDrawer(GravityCompat.START);
555 if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
556 mainModel.getAccountFilter()
558 showAccountSummaryFragment();
559 mBackMeansToAccountList = false;
562 Logger.debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
563 getSupportFragmentManager().getBackStackEntryCount()));
565 super.onBackPressed();
569 public void updateLastUpdateTextFromDB() {
573 long last_update = profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
575 Logger.debug("transactions",
576 String.format(Locale.ENGLISH, "Last update = %d", last_update));
577 if (last_update == 0) {
578 mainModel.lastUpdateDate.postValue(null);
581 mainModel.lastUpdateDate.postValue(new Date(last_update));
584 public void onStopTransactionRefreshClick(View view) {
585 Logger.debug("interactive", "Cancelling transactions refresh");
586 mainModel.stopTransactionsRetrieval();
587 bTransactionListCancelDownload.setEnabled(false);
589 public void onRetrieveRunningChanged(Boolean running) {
590 final View progressLayout = findViewById(R.id.transaction_progress_layout);
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);
602 progressBar.setProgress(0);
604 progressLayout.setVisibility(View.VISIBLE);
607 progressLayout.setVisibility(View.GONE);
610 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
611 ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
613 if (progress.getState() == RetrieveTransactionsTask.ProgressState.FINISHED) {
614 Logger.debug("progress", "Done");
615 findViewById(R.id.transaction_progress_layout).setVisibility(View.GONE);
617 mainModel.transactionRetrievalDone();
619 if (progress.getError() != null) {
620 Snackbar.make(mViewPager, progress.getError(), Snackbar.LENGTH_LONG)
629 bTransactionListCancelDownload.setEnabled(true);
630 // ColorStateList csl = Colors.getColorStateList();
631 // progressBar.setIndeterminateTintList(csl);
632 // progressBar.setProgressTintList(csl);
633 // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
634 // progressBar.setProgress(0, false);
636 // progressBar.setProgress(0);
637 findViewById(R.id.transaction_progress_layout).setVisibility(View.VISIBLE);
639 if (progress.isIndeterminate() || (progress.getTotal() <= 0)) {
640 progressBar.setIndeterminate(true);
641 Logger.debug("progress", "indeterminate");
644 if (progressBar.isIndeterminate()) {
645 progressBar.setIndeterminate(false);
647 // Logger.debug("progress",
648 // String.format(Locale.US, "%d/%d", progress.getProgress(), progress.getTotal
650 progressBar.setMax(progress.getTotal());
651 // for some reason animation doesn't work - no progress is shown (stick at 0)
652 // on lineageOS 14.1 (Nougat, 7.1.2)
653 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
654 progressBar.setProgress(progress.getProgress(), false);
656 progressBar.setProgress(progress.getProgress());
659 public void fabShouldShow() {
660 if ((profile != null) && profile.isPostingPermitted() && !drawer.isOpen())
665 public void fabHide() {
669 public static class SectionsPagerAdapter extends FragmentPagerAdapter {
671 SectionsPagerAdapter(FragmentManager fm) {
672 super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
677 public Fragment getItem(int position) {
679 String.format(Locale.ENGLISH, "Switching to fragment %d", position));
682 // debug("flow", "Creating account summary fragment");
683 return new AccountSummaryFragment();
685 return new TransactionListFragment();
687 throw new IllegalStateException(
688 String.format("Unexpected fragment index: " + "%d", position));
693 public int getCount() {