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.GetOptCallback;
65 import net.ktnx.mobileledger.utils.Logger;
66 import net.ktnx.mobileledger.utils.MLDB;
68 import org.jetbrains.annotations.NotNull;
70 import java.text.DateFormat;
71 import java.util.ArrayList;
72 import java.util.Date;
73 import java.util.List;
74 import java.util.Locale;
76 import static net.ktnx.mobileledger.utils.Logger.debug;
82 public class MainActivity extends ProfileThemedActivity {
83 public static final String STATE_CURRENT_PAGE = "current_page";
84 public static final String BUNDLE_SAVED_STATE = "bundle_savedState";
85 public static final String STATE_ACC_FILTER = "account_filter";
86 private static final String PREF_THEME_ID = "themeId";
88 private View profileListHeadMore, profileListHeadCancel, profileListHeadAddProfile;
89 private View bTransactionListCancelDownload;
90 private SectionsPagerAdapter mSectionsPagerAdapter;
91 private ViewPager mViewPager;
92 private FloatingActionButton fab;
93 private ProfilesRecyclerViewAdapter mProfileListAdapter;
94 private int mCurrentPage;
95 private boolean mBackMeansToAccountList = false;
96 private Toolbar mToolbar;
97 private DrawerLayout.SimpleDrawerListener drawerListener;
98 private ActionBarDrawerToggle barDrawerToggle;
99 private ViewPager.SimpleOnPageChangeListener pageChangeListener;
100 private MobileLedgerProfile profile;
102 protected void onStart() {
105 Logger.debug("MainActivity", "onStart()");
107 mViewPager.setCurrentItem(mCurrentPage, false);
110 protected void onSaveInstanceState(@NotNull Bundle outState) {
111 super.onSaveInstanceState(outState);
112 outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
113 if (Data.accountFilter.getValue() != null)
114 outState.putString(STATE_ACC_FILTER, Data.accountFilter.getValue());
117 protected void onDestroy() {
118 mSectionsPagerAdapter = null;
119 RecyclerView root = findViewById(R.id.nav_profile_list);
121 root.setAdapter(null);
123 drawer.removeDrawerListener(drawerListener);
124 drawerListener = null;
126 drawer.removeDrawerListener(barDrawerToggle);
127 barDrawerToggle = null;
128 if (mViewPager != null)
129 mViewPager.removeOnPageChangeListener(pageChangeListener);
130 pageChangeListener = null;
134 protected void setupProfileColors() {
135 SharedPreferences prefs = getPreferences(MODE_PRIVATE);
136 int profileColor = prefs.getInt(PREF_THEME_ID, -2);
137 if (profileColor == -2)
138 profileColor = Data.retrieveCurrentThemeIdFromDb();
139 Colors.setupTheme(this, profileColor);
140 Colors.profileThemeId = profileColor;
141 storeThemeIdInPrefs(profileColor);
144 protected void onResume() {
149 protected void onCreate(Bundle savedInstanceState) {
150 debug("MainActivity", "onCreate()/entry");
151 super.onCreate(savedInstanceState);
152 debug("MainActivity", "onCreate()/after super");
153 setContentView(R.layout.activity_main);
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.profile.observe(this, this::onProfileChanged);
176 Data.profiles.observe(this, this::onProfileListChanged);
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.profile.removeObservers(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 private void setupProfile() {
496 MLDB.getOption(MLDB.OPT_PROFILE_UUID, null, new GetOptCallback() {
498 protected void onResult(String profileUUID) {
499 MobileLedgerProfile startupProfile;
501 startupProfile = Data.getProfile(profileUUID);
502 Data.setCurrentProfile(startupProfile);
506 public void fabNewTransactionClicked(View view) {
507 Intent intent = new Intent(this, NewTransactionActivity.class);
508 startActivity(intent);
509 overridePendingTransition(R.anim.slide_in_up, R.anim.dummy);
511 public void markDrawerItemCurrent(int id) {
512 TextView item = drawer.findViewById(id);
513 item.setBackgroundColor(Colors.tableRowDarkBG);
515 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
516 for (int i = 0; i < actions.getChildCount(); i++) {
517 View view = actions.getChildAt(i);
518 if (view.getId() != id) {
519 view.setBackgroundColor(Color.TRANSPARENT);
523 public void onAccountSummaryClicked(View view) {
524 drawer.closeDrawers();
526 showAccountSummaryFragment();
528 private void showAccountSummaryFragment() {
529 mViewPager.setCurrentItem(0, true);
530 Data.accountFilter.setValue(null);
532 public void onLatestTransactionsClicked(View view) {
533 drawer.closeDrawers();
535 showTransactionsFragment(null);
537 public void showTransactionsFragment(String accName) {
538 Data.accountFilter.setValue(accName);
539 mViewPager.setCurrentItem(1, true);
541 public void showAccountTransactions(String accountName) {
542 mBackMeansToAccountList = true;
543 showTransactionsFragment(accountName);
546 public void onBackPressed() {
547 DrawerLayout drawer = findViewById(R.id.drawer_layout);
548 if (drawer.isDrawerOpen(GravityCompat.START)) {
549 drawer.closeDrawer(GravityCompat.START);
552 if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
553 Data.accountFilter.setValue(null);
554 showAccountSummaryFragment();
555 mBackMeansToAccountList = false;
558 debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
559 getSupportFragmentManager().getBackStackEntryCount()));
561 super.onBackPressed();
565 public void updateLastUpdateTextFromDB() {
569 long last_update = profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
571 debug("transactions", String.format(Locale.ENGLISH, "Last update = %d", last_update));
572 if (last_update == 0) {
573 Data.lastUpdateDate.postValue(null);
576 Data.lastUpdateDate.postValue(new Date(last_update));
579 public void onStopTransactionRefreshClick(View view) {
580 debug("interactive", "Cancelling transactions refresh");
581 Data.stopTransactionsRetrieval();
582 bTransactionListCancelDownload.setEnabled(false);
584 public void onRetrieveDone(String error) {
585 Data.transactionRetrievalDone();
586 findViewById(R.id.transaction_progress_layout).setVisibility(View.GONE);
589 updateLastUpdateTextFromDB();
591 new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
592 TransactionListViewModel.scheduleTransactionListReload();
595 Snackbar.make(mViewPager, error, Snackbar.LENGTH_LONG)
598 public void onRetrieveStart() {
599 ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
600 bTransactionListCancelDownload.setEnabled(true);
601 ColorStateList csl = Colors.getColorStateList();
602 progressBar.setIndeterminateTintList(csl);
603 progressBar.setProgressTintList(csl);
604 progressBar.setIndeterminate(true);
605 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
606 progressBar.setProgress(0, false);
608 progressBar.setProgress(0);
609 findViewById(R.id.transaction_progress_layout).setVisibility(View.VISIBLE);
611 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
612 ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
613 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
614 (progress.getTotal() == 0))
616 progressBar.setIndeterminate(true);
619 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
620 progressBar.setMin(0);
622 progressBar.setMax(progress.getTotal());
623 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
624 progressBar.setProgress(progress.getProgress(), true);
627 progressBar.setProgress(progress.getProgress());
628 progressBar.setIndeterminate(false);
631 public void fabShouldShow() {
632 if ((profile != null) && profile.isPostingPermitted() && !drawer.isOpen())
637 public void fabHide() {
641 public static class SectionsPagerAdapter extends FragmentPagerAdapter {
643 SectionsPagerAdapter(FragmentManager fm) {
644 super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
649 public Fragment getItem(int position) {
650 debug("main", String.format(Locale.ENGLISH, "Switching to fragment %d", position));
653 // debug("flow", "Creating account summary fragment");
654 return new AccountSummaryFragment();
656 return new TransactionListFragment();
658 throw new IllegalStateException(
659 String.format("Unexpected fragment index: " + "%d", position));
664 public int getCount() {