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);
177 Data.backgroundTasksRunning.observe(this, this::onRetrieveRunningChanged);
179 if (barDrawerToggle == null) {
180 barDrawerToggle = new ActionBarDrawerToggle(this, drawer, mToolbar,
181 R.string.navigation_drawer_open, R.string.navigation_drawer_close);
182 drawer.addDrawerListener(barDrawerToggle);
184 barDrawerToggle.syncState();
187 PackageInfo pi = getApplicationContext().getPackageManager()
188 .getPackageInfo(getPackageName(), 0);
189 ((TextView) findViewById(R.id.nav_upper).findViewById(
190 R.id.drawer_version_text)).setText(pi.versionName);
191 ((TextView) findViewById(R.id.no_profiles_layout).findViewById(
192 R.id.drawer_version_text)).setText(pi.versionName);
194 catch (Exception e) {
198 markDrawerItemCurrent(R.id.nav_account_summary);
200 mViewPager.setAdapter(mSectionsPagerAdapter);
202 if (pageChangeListener == null) {
203 pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
205 public void onPageSelected(int position) {
206 mCurrentPage = position;
209 markDrawerItemCurrent(R.id.nav_account_summary);
212 markDrawerItemCurrent(R.id.nav_latest_transactions);
215 Log.e("MainActivity",
216 String.format("Unexpected page index %d", position));
219 super.onPageSelected(position);
222 mViewPager.addOnPageChangeListener(pageChangeListener);
226 if (savedInstanceState != null) {
227 int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
228 if (currentPage != -1) {
229 mCurrentPage = currentPage;
231 Data.accountFilter.setValue(savedInstanceState.getString(STATE_ACC_FILTER, null));
234 Data.lastUpdateDate.observe(this, this::updateLastUpdateDisplay);
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 private void scheduleDataRetrievalIfStale(Date lastUpdate) {
326 long now = new Date().getTime();
327 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
328 if (lastUpdate == null)
329 debug("db::", "WEB data never fetched. scheduling a fetch");
331 debug("db", String.format(Locale.ENGLISH,
332 "WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
333 lastUpdate.getTime() / 1000f, now / 1000f));
335 scheduleDataRetrieval();
338 public void scheduleDataRetrieval() {
339 Data.scheduleTransactionListRetrieval();
341 private void createShortcuts(List<MobileLedgerProfile> list) {
342 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
345 ShortcutManager sm = getSystemService(ShortcutManager.class);
346 List<ShortcutInfo> shortcuts = new ArrayList<>();
348 for (MobileLedgerProfile p : list) {
349 if (shortcuts.size() >= sm.getMaxShortcutCountPerActivity())
352 if (!p.isPostingPermitted())
355 final ShortcutInfo.Builder builder =
356 new ShortcutInfo.Builder(this, "new_transaction_" + p.getUuid());
357 ShortcutInfo si = builder.setShortLabel(p.getName())
358 .setIcon(Icon.createWithResource(this,
359 R.drawable.thick_plus_icon))
360 .setIntent(new Intent(Intent.ACTION_VIEW, null, this,
361 NewTransactionActivity.class).putExtra("profile_uuid",
368 sm.setDynamicShortcuts(shortcuts);
370 private void onProfileListChanged(List<MobileLedgerProfile> newList) {
371 if ((newList == null) || newList.isEmpty()) {
372 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
373 findViewById(R.id.main_app_layout).setVisibility(View.GONE);
377 findViewById(R.id.main_app_layout).setVisibility(View.VISIBLE);
378 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
380 findViewById(R.id.nav_profile_list).setMinimumHeight(
381 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
383 debug("profiles", "profile list changed");
384 mProfileListAdapter.notifyDataSetChanged();
386 createShortcuts(newList);
389 * called when the current profile has changed
391 private void onProfileChanged(MobileLedgerProfile profile) {
392 if (this.profile == null) {
397 if (this.profile.equals(profile))
401 boolean haveProfile = profile != null;
404 setTitle(profile.getName());
406 setTitle(R.string.app_name);
408 if (this.profile != null)
409 this.profile.getDisplayedAccounts()
410 .removeObservers(this);
412 this.profile = profile;
414 int newProfileTheme = haveProfile ? profile.getThemeHue() : -1;
415 if (newProfileTheme != Colors.profileThemeId) {
417 String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
419 Colors.profileThemeId = newProfileTheme;
420 profileThemeChanged();
421 // profileThemeChanged would restart the activity, so no need to reload the
426 findViewById(R.id.no_profiles_layout).setVisibility(haveProfile ? View.GONE : View.VISIBLE);
427 findViewById(R.id.pager_layout).setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
429 mProfileListAdapter.notifyDataSetChanged();
431 Data.transactions.clear();
432 debug("transactions", "requesting list reload");
433 TransactionListViewModel.scheduleTransactionListReload();
436 profile.scheduleAccountListReload();
438 if (profile.isPostingPermitted()) {
439 mToolbar.setSubtitle(null);
443 mToolbar.setSubtitle(R.string.profile_subtitle_read_only);
448 mToolbar.setSubtitle(null);
452 updateLastUpdateTextFromDB();
454 private void updateLastUpdateDisplay(Date newValue) {
455 LinearLayout l = findViewById(R.id.transactions_last_update_layout);
456 TextView v = findViewById(R.id.transactions_last_update);
457 if (newValue == null) {
458 l.setVisibility(View.INVISIBLE);
459 debug("main", "no last update date :(");
462 final String text = DateFormat.getDateTimeInstance()
465 l.setVisibility(View.VISIBLE);
466 debug("main", String.format("Date formatted: %s", text));
469 scheduleDataRetrievalIfStale(newValue);
471 private void profileThemeChanged() {
472 storeThemeIdInPrefs(profile.getThemeHue());
474 // un-hook all observed LiveData
475 Data.removeProfileObservers(this);
476 Data.profiles.removeObservers(this);
477 Data.lastUpdateDate.removeObservers(this);
481 private void storeThemeIdInPrefs(int themeId) {
482 // store the new theme id in the preferences
483 SharedPreferences prefs = getPreferences(MODE_PRIVATE);
484 SharedPreferences.Editor e = prefs.edit();
485 e.putInt(PREF_THEME_ID, themeId);
488 public void startEditProfileActivity(MobileLedgerProfile profile) {
489 Intent intent = new Intent(this, ProfileDetailActivity.class);
490 Bundle args = new Bundle();
491 if (profile != null) {
492 int index = Data.getProfileIndex(profile);
494 intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
496 intent.putExtras(args);
497 startActivity(intent, args);
499 public void fabNewTransactionClicked(View view) {
500 Intent intent = new Intent(this, NewTransactionActivity.class);
501 startActivity(intent);
502 overridePendingTransition(R.anim.slide_in_up, R.anim.dummy);
504 public void markDrawerItemCurrent(int id) {
505 TextView item = drawer.findViewById(id);
506 item.setBackgroundColor(Colors.tableRowDarkBG);
508 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
509 for (int i = 0; i < actions.getChildCount(); i++) {
510 View view = actions.getChildAt(i);
511 if (view.getId() != id) {
512 view.setBackgroundColor(Color.TRANSPARENT);
516 public void onAccountSummaryClicked(View view) {
517 drawer.closeDrawers();
519 showAccountSummaryFragment();
521 private void showAccountSummaryFragment() {
522 mViewPager.setCurrentItem(0, true);
523 Data.accountFilter.setValue(null);
525 public void onLatestTransactionsClicked(View view) {
526 drawer.closeDrawers();
528 showTransactionsFragment(null);
530 public void showTransactionsFragment(String accName) {
531 Data.accountFilter.setValue(accName);
532 mViewPager.setCurrentItem(1, true);
534 public void showAccountTransactions(String accountName) {
535 mBackMeansToAccountList = true;
536 showTransactionsFragment(accountName);
539 public void onBackPressed() {
540 DrawerLayout drawer = findViewById(R.id.drawer_layout);
541 if (drawer.isDrawerOpen(GravityCompat.START)) {
542 drawer.closeDrawer(GravityCompat.START);
545 if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
546 Data.accountFilter.setValue(null);
547 showAccountSummaryFragment();
548 mBackMeansToAccountList = false;
551 debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
552 getSupportFragmentManager().getBackStackEntryCount()));
554 super.onBackPressed();
558 public void updateLastUpdateTextFromDB() {
562 long last_update = profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
564 debug("transactions", String.format(Locale.ENGLISH, "Last update = %d", last_update));
565 if (last_update == 0) {
566 Data.lastUpdateDate.postValue(null);
569 Data.lastUpdateDate.postValue(new Date(last_update));
572 public void onStopTransactionRefreshClick(View view) {
573 debug("interactive", "Cancelling transactions refresh");
574 Data.stopTransactionsRetrieval();
575 bTransactionListCancelDownload.setEnabled(false);
577 public void onRetrieveRunningChanged(Boolean running) {
578 final View progressLayout = findViewById(R.id.transaction_progress_layout);
580 ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
581 bTransactionListCancelDownload.setEnabled(true);
582 ColorStateList csl = Colors.getColorStateList();
583 progressBar.setIndeterminateTintList(csl);
584 progressBar.setProgressTintList(csl);
585 progressBar.setIndeterminate(true);
586 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
587 progressBar.setProgress(0, false);
590 progressBar.setProgress(0);
592 progressLayout.setVisibility(View.VISIBLE);
595 progressLayout.setVisibility(View.GONE);
598 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
599 ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
601 if (progress.getState() == RetrieveTransactionsTask.ProgressState.FINISHED) {
602 Logger.debug("progress", "Done");
603 findViewById(R.id.transaction_progress_layout).setVisibility(View.GONE);
605 Data.transactionRetrievalDone();
607 if (progress.getError() != null) {
608 Snackbar.make(mViewPager, progress.getError(), Snackbar.LENGTH_LONG)
613 updateLastUpdateTextFromDB();
615 new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
616 TransactionListViewModel.scheduleTransactionListReload();
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 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
638 progressBar.setMin(0);
640 Logger.debug("progress",
641 String.format(Locale.US, "%d/%d", progress.getProgress(), progress.getTotal()));
642 progressBar.setMax(progress.getTotal());
643 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
644 progressBar.setProgress(progress.getProgress(), true);
647 progressBar.setProgress(progress.getProgress());
648 progressBar.setIndeterminate(false);
651 public void fabShouldShow() {
652 if ((profile != null) && profile.isPostingPermitted() && !drawer.isOpen())
657 public void fabHide() {
661 public static class SectionsPagerAdapter extends FragmentPagerAdapter {
663 SectionsPagerAdapter(FragmentManager fm) {
664 super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
669 public Fragment getItem(int position) {
670 debug("main", String.format(Locale.ENGLISH, "Switching to fragment %d", position));
673 // debug("flow", "Creating account summary fragment");
674 return new AccountSummaryFragment();
676 return new TransactionListFragment();
678 throw new IllegalStateException(
679 String.format("Unexpected fragment index: " + "%d", position));
684 public int getCount() {