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.animation.AnimationUtils;
34 import android.widget.LinearLayout;
35 import android.widget.ProgressBar;
36 import android.widget.TextView;
38 import androidx.annotation.NonNull;
39 import androidx.appcompat.app.ActionBarDrawerToggle;
40 import androidx.appcompat.widget.Toolbar;
41 import androidx.core.view.GravityCompat;
42 import androidx.drawerlayout.widget.DrawerLayout;
43 import androidx.fragment.app.Fragment;
44 import androidx.fragment.app.FragmentManager;
45 import androidx.fragment.app.FragmentPagerAdapter;
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.RefreshDescriptionsTask;
55 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
56 import net.ktnx.mobileledger.model.Data;
57 import net.ktnx.mobileledger.model.MobileLedgerProfile;
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.ui.transaction_list.TransactionListViewModel;
63 import net.ktnx.mobileledger.utils.Colors;
64 import net.ktnx.mobileledger.utils.Logger;
65 import net.ktnx.mobileledger.utils.MLDB;
67 import org.jetbrains.annotations.NotNull;
69 import java.text.DateFormat;
70 import java.util.ArrayList;
71 import java.util.Date;
72 import java.util.List;
73 import java.util.Locale;
75 import static net.ktnx.mobileledger.utils.Logger.debug;
81 public class MainActivity extends ProfileThemedActivity {
82 public static final String STATE_CURRENT_PAGE = "current_page";
83 public static final String BUNDLE_SAVED_STATE = "bundle_savedState";
84 public static final String STATE_ACC_FILTER = "account_filter";
85 private static final String PREF_THEME_ID = "themeId";
87 private View profileListHeadMore, profileListHeadCancel, profileListHeadAddProfile;
88 private View bTransactionListCancelDownload;
89 private SectionsPagerAdapter mSectionsPagerAdapter;
90 private ViewPager mViewPager;
91 private FloatingActionButton fab;
92 private ProfilesRecyclerViewAdapter mProfileListAdapter;
93 private int mCurrentPage;
94 private boolean mBackMeansToAccountList = false;
95 private Toolbar mToolbar;
96 private DrawerLayout.SimpleDrawerListener drawerListener;
97 private ActionBarDrawerToggle barDrawerToggle;
98 private ViewPager.SimpleOnPageChangeListener pageChangeListener;
99 private MobileLedgerProfile profile;
101 protected void onStart() {
104 Logger.debug("MainActivity", "onStart()");
106 mViewPager.setCurrentItem(mCurrentPage, false);
109 protected void onSaveInstanceState(@NotNull Bundle outState) {
110 super.onSaveInstanceState(outState);
111 outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
112 if (Data.accountFilter.getValue() != null)
113 outState.putString(STATE_ACC_FILTER, Data.accountFilter.getValue());
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 debug("MainActivity", "onCreate()/entry");
150 super.onCreate(savedInstanceState);
151 debug("MainActivity", "onCreate()/after super");
152 setContentView(R.layout.activity_main);
154 fab = findViewById(R.id.btn_add_transaction);
155 profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
156 profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
157 LinearLayout profileListHeadMoreAndCancel =
158 findViewById(R.id.nav_profile_list_head_buttons);
159 profileListHeadAddProfile = findViewById(R.id.nav_new_profile_button);
160 drawer = findViewById(R.id.drawer_layout);
161 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
162 mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
163 mViewPager = findViewById(R.id.root_frame);
165 Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
166 if (extra != null && savedInstanceState == null)
167 savedInstanceState = extra;
170 mToolbar = findViewById(R.id.toolbar);
171 setSupportActionBar(mToolbar);
173 Data.observeProfile(this, this::onProfileChanged);
175 Data.profiles.observe(this, this::onProfileListChanged);
176 Data.backgroundTaskProgress.observe(this, this::onRetrieveProgress);
178 if (barDrawerToggle == null) {
179 barDrawerToggle = new ActionBarDrawerToggle(this, drawer, mToolbar,
180 R.string.navigation_drawer_open, R.string.navigation_drawer_close);
181 drawer.addDrawerListener(barDrawerToggle);
183 barDrawerToggle.syncState();
186 PackageInfo pi = getApplicationContext().getPackageManager()
187 .getPackageInfo(getPackageName(), 0);
188 ((TextView) findViewById(R.id.nav_upper).findViewById(
189 R.id.drawer_version_text)).setText(pi.versionName);
190 ((TextView) findViewById(R.id.no_profiles_layout).findViewById(
191 R.id.drawer_version_text)).setText(pi.versionName);
193 catch (Exception e) {
197 markDrawerItemCurrent(R.id.nav_account_summary);
199 mViewPager.setAdapter(mSectionsPagerAdapter);
201 if (pageChangeListener == null) {
202 pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
204 public void onPageSelected(int position) {
205 mCurrentPage = position;
208 markDrawerItemCurrent(R.id.nav_account_summary);
211 markDrawerItemCurrent(R.id.nav_latest_transactions);
214 Log.e("MainActivity",
215 String.format("Unexpected page index %d", position));
218 super.onPageSelected(position);
221 mViewPager.addOnPageChangeListener(pageChangeListener);
225 if (savedInstanceState != null) {
226 int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
227 if (currentPage != -1) {
228 mCurrentPage = currentPage;
230 Data.accountFilter.setValue(savedInstanceState.getString(STATE_ACC_FILTER, null));
233 Data.lastUpdateDate.observe(this, this::updateLastUpdateDisplay);
235 findViewById(R.id.btn_no_profiles_add).setOnClickListener(
236 v -> startEditProfileActivity(null));
238 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
240 findViewById(R.id.nav_new_profile_button).setOnClickListener(
241 v -> startEditProfileActivity(null));
243 RecyclerView root = findViewById(R.id.nav_profile_list);
245 throw new RuntimeException("Can't get hold on the transaction value view");
247 if (mProfileListAdapter == null)
248 mProfileListAdapter = new ProfilesRecyclerViewAdapter();
249 root.setAdapter(mProfileListAdapter);
251 mProfileListAdapter.editingProfiles.observe(this, newValue -> {
253 profileListHeadMore.setVisibility(View.GONE);
254 profileListHeadCancel.setVisibility(View.VISIBLE);
255 profileListHeadAddProfile.setVisibility(View.VISIBLE);
256 if (drawer.isDrawerOpen(GravityCompat.START)) {
257 profileListHeadMore.startAnimation(
258 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
259 profileListHeadCancel.startAnimation(
260 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
261 profileListHeadAddProfile.startAnimation(
262 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
266 profileListHeadCancel.setVisibility(View.GONE);
267 profileListHeadMore.setVisibility(View.VISIBLE);
268 profileListHeadAddProfile.setVisibility(View.GONE);
269 if (drawer.isDrawerOpen(GravityCompat.START)) {
270 profileListHeadCancel.startAnimation(
271 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
272 profileListHeadMore.startAnimation(
273 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
274 profileListHeadAddProfile.startAnimation(
275 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
279 mProfileListAdapter.notifyDataSetChanged();
282 LinearLayoutManager llm = new LinearLayoutManager(this);
284 llm.setOrientation(RecyclerView.VERTICAL);
285 root.setLayoutManager(llm);
287 profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
288 profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
289 profileListHeadMoreAndCancel.setOnClickListener(
290 (v) -> mProfileListAdapter.flipEditingProfiles());
291 if (drawerListener == null) {
292 drawerListener = new DrawerLayout.SimpleDrawerListener() {
294 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
295 if (slideOffset > 0.2)
299 public void onDrawerClosed(View drawerView) {
300 super.onDrawerClosed(drawerView);
301 mProfileListAdapter.setAnimationsEnabled(false);
302 mProfileListAdapter.editingProfiles.setValue(false);
303 Data.drawerOpen.setValue(false);
307 public void onDrawerOpened(View drawerView) {
308 super.onDrawerOpened(drawerView);
309 mProfileListAdapter.setAnimationsEnabled(true);
310 Data.drawerOpen.setValue(true);
314 drawer.addDrawerListener(drawerListener);
317 Data.drawerOpen.observe(this, open -> {
324 private void scheduleDataRetrievalIfStale(Date lastUpdate) {
325 long now = new Date().getTime();
326 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
327 if (lastUpdate == null)
328 debug("db::", "WEB data never fetched. scheduling a fetch");
330 debug("db", String.format(Locale.ENGLISH,
331 "WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
332 lastUpdate.getTime() / 1000f, now / 1000f));
334 Data.scheduleTransactionListRetrieval(this);
337 private void createShortcuts(List<MobileLedgerProfile> list) {
338 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
341 ShortcutManager sm = getSystemService(ShortcutManager.class);
342 List<ShortcutInfo> shortcuts = new ArrayList<>();
344 for (MobileLedgerProfile p : list) {
345 if (shortcuts.size() >= sm.getMaxShortcutCountPerActivity())
348 if (!p.isPostingPermitted())
351 final ShortcutInfo.Builder builder =
352 new ShortcutInfo.Builder(this, "new_transaction_" + p.getUuid());
353 ShortcutInfo si = builder.setShortLabel(p.getName())
354 .setIcon(Icon.createWithResource(this,
355 R.drawable.thick_plus_icon))
356 .setIntent(new Intent(Intent.ACTION_VIEW, null, this,
357 NewTransactionActivity.class).putExtra("profile_uuid",
364 sm.setDynamicShortcuts(shortcuts);
366 private void onProfileListChanged(List<MobileLedgerProfile> newList) {
367 if ((newList == null) || newList.isEmpty()) {
368 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
369 findViewById(R.id.main_app_layout).setVisibility(View.GONE);
373 findViewById(R.id.main_app_layout).setVisibility(View.VISIBLE);
374 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
376 findViewById(R.id.nav_profile_list).setMinimumHeight(
377 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
379 debug("profiles", "profile list changed");
380 mProfileListAdapter.notifyDataSetChanged();
382 createShortcuts(newList);
385 * called when the current profile has changed
387 private void onProfileChanged(MobileLedgerProfile profile) {
388 if (this.profile == null) {
393 if (this.profile.equals(profile))
397 boolean haveProfile = profile != null;
400 setTitle(profile.getName());
402 setTitle(R.string.app_name);
404 if (this.profile != null)
405 this.profile.getDisplayedAccounts()
406 .removeObservers(this);
408 this.profile = profile;
410 int newProfileTheme = haveProfile ? profile.getThemeHue() : -1;
411 if (newProfileTheme != Colors.profileThemeId) {
413 String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
415 Colors.profileThemeId = newProfileTheme;
416 profileThemeChanged();
417 // profileThemeChanged would restart the activity, so no need to reload the
422 findViewById(R.id.no_profiles_layout).setVisibility(haveProfile ? View.GONE : View.VISIBLE);
423 findViewById(R.id.pager_layout).setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
425 mProfileListAdapter.notifyDataSetChanged();
427 Data.transactions.clear();
428 debug("transactions", "requesting list reload");
429 TransactionListViewModel.scheduleTransactionListReload();
432 profile.scheduleAccountListReload();
434 if (profile.isPostingPermitted()) {
435 mToolbar.setSubtitle(null);
439 mToolbar.setSubtitle(R.string.profile_subtitle_read_only);
444 mToolbar.setSubtitle(null);
448 updateLastUpdateTextFromDB();
450 private void updateLastUpdateDisplay(Date newValue) {
451 LinearLayout l = findViewById(R.id.transactions_last_update_layout);
452 TextView v = findViewById(R.id.transactions_last_update);
453 if (newValue == null) {
454 l.setVisibility(View.INVISIBLE);
455 debug("main", "no last update date :(");
458 final String text = DateFormat.getDateTimeInstance()
461 l.setVisibility(View.VISIBLE);
462 debug("main", String.format("Date formatted: %s", text));
465 scheduleDataRetrievalIfStale(newValue);
467 private void profileThemeChanged() {
468 storeThemeIdInPrefs(profile.getThemeHue());
470 // un-hook all observed LiveData
471 Data.removeProfileObservers(this);
472 Data.profiles.removeObservers(this);
473 Data.lastUpdateDate.removeObservers(this);
477 private void storeThemeIdInPrefs(int themeId) {
478 // store the new theme id in the preferences
479 SharedPreferences prefs = getPreferences(MODE_PRIVATE);
480 SharedPreferences.Editor e = prefs.edit();
481 e.putInt(PREF_THEME_ID, themeId);
484 public void startEditProfileActivity(MobileLedgerProfile profile) {
485 Intent intent = new Intent(this, ProfileDetailActivity.class);
486 Bundle args = new Bundle();
487 if (profile != null) {
488 int index = Data.getProfileIndex(profile);
490 intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
492 intent.putExtras(args);
493 startActivity(intent, args);
495 public void fabNewTransactionClicked(View view) {
496 Intent intent = new Intent(this, NewTransactionActivity.class);
497 startActivity(intent);
498 overridePendingTransition(R.anim.slide_in_up, R.anim.dummy);
500 public void markDrawerItemCurrent(int id) {
501 TextView item = drawer.findViewById(id);
502 item.setBackgroundColor(Colors.tableRowDarkBG);
504 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
505 for (int i = 0; i < actions.getChildCount(); i++) {
506 View view = actions.getChildAt(i);
507 if (view.getId() != id) {
508 view.setBackgroundColor(Color.TRANSPARENT);
512 public void onAccountSummaryClicked(View view) {
513 drawer.closeDrawers();
515 showAccountSummaryFragment();
517 private void showAccountSummaryFragment() {
518 mViewPager.setCurrentItem(0, true);
519 Data.accountFilter.setValue(null);
521 public void onLatestTransactionsClicked(View view) {
522 drawer.closeDrawers();
524 showTransactionsFragment(null);
526 public void showTransactionsFragment(String accName) {
527 Data.accountFilter.setValue(accName);
528 mViewPager.setCurrentItem(1, true);
530 public void showAccountTransactions(String accountName) {
531 mBackMeansToAccountList = true;
532 showTransactionsFragment(accountName);
535 public void onBackPressed() {
536 DrawerLayout drawer = findViewById(R.id.drawer_layout);
537 if (drawer.isDrawerOpen(GravityCompat.START)) {
538 drawer.closeDrawer(GravityCompat.START);
541 if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
542 Data.accountFilter.setValue(null);
543 showAccountSummaryFragment();
544 mBackMeansToAccountList = false;
547 debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
548 getSupportFragmentManager().getBackStackEntryCount()));
550 super.onBackPressed();
554 public void updateLastUpdateTextFromDB() {
558 long last_update = profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
560 debug("transactions", String.format(Locale.ENGLISH, "Last update = %d", last_update));
561 if (last_update == 0) {
562 Data.lastUpdateDate.postValue(null);
565 Data.lastUpdateDate.postValue(new Date(last_update));
568 public void onStopTransactionRefreshClick(View view) {
569 debug("interactive", "Cancelling transactions refresh");
570 Data.stopTransactionsRetrieval();
571 bTransactionListCancelDownload.setEnabled(false);
573 public void onRetrieveStart() {
574 ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
575 bTransactionListCancelDownload.setEnabled(true);
576 ColorStateList csl = Colors.getColorStateList();
577 progressBar.setIndeterminateTintList(csl);
578 progressBar.setProgressTintList(csl);
579 progressBar.setIndeterminate(true);
580 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
581 progressBar.setProgress(0, false);
583 progressBar.setProgress(0);
584 findViewById(R.id.transaction_progress_layout).setVisibility(View.VISIBLE);
586 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
587 ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
589 if (progress.getState() == RetrieveTransactionsTask.ProgressState.FINISHED) {
590 findViewById(R.id.transaction_progress_layout).setVisibility(View.GONE);
592 Data.transactionRetrievalDone();
594 if (progress.getError() != null) {
595 Snackbar.make(mViewPager, progress.getError(), Snackbar.LENGTH_LONG)
600 updateLastUpdateTextFromDB();
602 new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
603 TransactionListViewModel.scheduleTransactionListReload();
609 bTransactionListCancelDownload.setEnabled(true);
610 ColorStateList csl = Colors.getColorStateList();
611 progressBar.setIndeterminateTintList(csl);
612 progressBar.setProgressTintList(csl);
613 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
614 progressBar.setProgress(0, false);
616 progressBar.setProgress(0);
617 findViewById(R.id.transaction_progress_layout).setVisibility(View.VISIBLE);
619 if (progress.isIndeterminate() || (progress.getTotal() == 0)) {
620 progressBar.setIndeterminate(true);
623 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
624 progressBar.setMin(0);
626 progressBar.setMax(progress.getTotal());
627 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
628 progressBar.setProgress(progress.getProgress(), true);
631 progressBar.setProgress(progress.getProgress());
632 progressBar.setIndeterminate(false);
635 public void fabShouldShow() {
636 if ((profile != null) && profile.isPostingPermitted() && !drawer.isOpen())
641 public void fabHide() {
645 public static class SectionsPagerAdapter extends FragmentPagerAdapter {
647 SectionsPagerAdapter(FragmentManager fm) {
648 super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
653 public Fragment getItem(int position) {
654 debug("main", String.format(Locale.ENGLISH, "Switching to fragment %d", position));
657 // debug("flow", "Creating account summary fragment");
658 return new AccountSummaryFragment();
660 return new TransactionListFragment();
662 throw new IllegalStateException(
663 String.format("Unexpected fragment index: " + "%d", position));
668 public int getCount() {