2 * Copyright © 2021 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.pm.PackageInfo;
22 import android.content.pm.ShortcutInfo;
23 import android.content.pm.ShortcutManager;
24 import android.content.res.ColorStateList;
25 import android.graphics.Color;
26 import android.graphics.drawable.Icon;
27 import android.os.Build;
28 import android.os.Bundle;
29 import android.text.format.DateUtils;
30 import android.util.Log;
31 import android.view.View;
32 import android.view.animation.AnimationUtils;
33 import android.widget.TextView;
35 import androidx.annotation.NonNull;
36 import androidx.appcompat.app.ActionBarDrawerToggle;
37 import androidx.appcompat.app.AlertDialog;
38 import androidx.core.view.GravityCompat;
39 import androidx.drawerlayout.widget.DrawerLayout;
40 import androidx.fragment.app.Fragment;
41 import androidx.fragment.app.FragmentActivity;
42 import androidx.lifecycle.ViewModelProvider;
43 import androidx.recyclerview.widget.LinearLayoutManager;
44 import androidx.recyclerview.widget.RecyclerView;
45 import androidx.viewpager2.adapter.FragmentStateAdapter;
46 import androidx.viewpager2.widget.ViewPager2;
48 import com.google.android.material.snackbar.Snackbar;
50 import net.ktnx.mobileledger.R;
51 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
52 import net.ktnx.mobileledger.databinding.ActivityMainBinding;
53 import net.ktnx.mobileledger.model.Data;
54 import net.ktnx.mobileledger.model.MobileLedgerProfile;
55 import net.ktnx.mobileledger.ui.MainModel;
56 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
57 import net.ktnx.mobileledger.ui.new_transaction.NewTransactionActivity;
58 import net.ktnx.mobileledger.ui.profiles.ProfilesRecyclerViewAdapter;
59 import net.ktnx.mobileledger.ui.templates.TemplatesActivity;
60 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
61 import net.ktnx.mobileledger.utils.Colors;
62 import net.ktnx.mobileledger.utils.Logger;
63 import net.ktnx.mobileledger.utils.MLDB;
65 import org.jetbrains.annotations.NotNull;
67 import java.util.ArrayList;
68 import java.util.Date;
69 import java.util.List;
70 import java.util.Locale;
71 import java.util.Objects;
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 SectionsPagerAdapter mSectionsPagerAdapter;
82 private ProfilesRecyclerViewAdapter mProfileListAdapter;
83 private int mCurrentPage;
84 private boolean mBackMeansToAccountList = false;
85 private DrawerLayout.SimpleDrawerListener drawerListener;
86 private ActionBarDrawerToggle barDrawerToggle;
87 private ViewPager2.OnPageChangeCallback pageChangeCallback;
88 private MobileLedgerProfile profile;
89 private MainModel mainModel;
90 private ActivityMainBinding b;
92 protected void onStart() {
95 Logger.debug("MainActivity", "onStart()");
97 b.mainPager.setCurrentItem(mCurrentPage, false);
100 protected void onSaveInstanceState(@NotNull Bundle outState) {
101 super.onSaveInstanceState(outState);
102 outState.putInt(STATE_CURRENT_PAGE, b.mainPager.getCurrentItem());
103 if (mainModel.getAccountFilter()
105 outState.putString(STATE_ACC_FILTER, mainModel.getAccountFilter()
109 protected void onDestroy() {
110 mSectionsPagerAdapter = null;
111 b.navProfileList.setAdapter(null);
112 b.drawerLayout.removeDrawerListener(drawerListener);
113 drawerListener = null;
114 b.drawerLayout.removeDrawerListener(barDrawerToggle);
115 barDrawerToggle = null;
116 b.mainPager.unregisterOnPageChangeCallback(pageChangeCallback);
117 pageChangeCallback = null;
121 protected void onResume() {
126 protected void onCreate(Bundle savedInstanceState) {
127 Logger.debug("MainActivity", "onCreate()/entry");
128 super.onCreate(savedInstanceState);
129 Logger.debug("MainActivity", "onCreate()/after super");
130 b = ActivityMainBinding.inflate(getLayoutInflater());
131 setContentView(b.getRoot());
133 mainModel = new ViewModelProvider(this).get(MainModel.class);
135 mSectionsPagerAdapter = new SectionsPagerAdapter(this);
137 Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
138 if (extra != null && savedInstanceState == null)
139 savedInstanceState = extra;
142 setSupportActionBar(b.toolbar);
144 Data.observeProfile(this, this::onProfileChanged);
146 Data.profiles.observe(this, this::onProfileListChanged);
147 Data.backgroundTaskProgress.observe(this, this::onRetrieveProgress);
148 Data.backgroundTasksRunning.observe(this, this::onRetrieveRunningChanged);
150 if (barDrawerToggle == null) {
151 barDrawerToggle = new ActionBarDrawerToggle(this, b.drawerLayout, b.toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
152 b.drawerLayout.addDrawerListener(barDrawerToggle);
154 barDrawerToggle.syncState();
157 PackageInfo pi = getApplicationContext().getPackageManager()
158 .getPackageInfo(getPackageName(), 0);
159 ((TextView) b.navUpper.findViewById(R.id.drawer_version_text)).setText(pi.versionName);
160 ((TextView) b.noProfilesLayout.findViewById(R.id.drawer_version_text)).setText(pi.versionName);
162 catch (Exception e) {
166 markDrawerItemCurrent(R.id.nav_account_summary);
168 b.mainPager.setAdapter(mSectionsPagerAdapter);
170 if (pageChangeCallback == null) {
171 pageChangeCallback = new ViewPager2.OnPageChangeCallback() {
173 public void onPageSelected(int position) {
174 mCurrentPage = position;
177 markDrawerItemCurrent(R.id.nav_account_summary);
180 markDrawerItemCurrent(R.id.nav_latest_transactions);
183 Log.e("MainActivity",
184 String.format("Unexpected page index %d", position));
187 super.onPageSelected(position);
190 b.mainPager.registerOnPageChangeCallback(pageChangeCallback);
194 if (savedInstanceState != null) {
195 int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
196 if (currentPage != -1) {
197 mCurrentPage = currentPage;
199 mainModel.getAccountFilter()
200 .setValue(savedInstanceState.getString(STATE_ACC_FILTER, null));
203 b.btnNoProfilesAdd.setOnClickListener(v -> MobileLedgerProfile.startEditProfileActivity(this, null));
205 b.btnAddTransaction.setOnClickListener(this::fabNewTransactionClicked);
207 b.navNewProfileButton.setOnClickListener(v -> MobileLedgerProfile.startEditProfileActivity(this, null));
209 b.transactionListCancelDownload.setOnClickListener(this::onStopTransactionRefreshClick);
211 if (mProfileListAdapter == null)
212 mProfileListAdapter = new ProfilesRecyclerViewAdapter();
213 b.navProfileList.setAdapter(mProfileListAdapter);
215 mProfileListAdapter.editingProfiles.observe(this, newValue -> {
217 b.navProfilesStartEdit.setVisibility(View.GONE);
218 b.navProfilesCancelEdit.setVisibility(View.VISIBLE);
219 b.navNewProfileButton.setVisibility(View.VISIBLE);
220 if (b.drawerLayout.isDrawerOpen(GravityCompat.START)) {
221 b.navProfilesStartEdit.startAnimation(
222 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
223 b.navProfilesCancelEdit.startAnimation(
224 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
225 b.navNewProfileButton.startAnimation(
226 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
230 b.navProfilesCancelEdit.setVisibility(View.GONE);
231 b.navProfilesStartEdit.setVisibility(View.VISIBLE);
232 b.navNewProfileButton.setVisibility(View.GONE);
233 if (b.drawerLayout.isDrawerOpen(GravityCompat.START)) {
234 b.navProfilesCancelEdit.startAnimation(
235 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
236 b.navProfilesStartEdit.startAnimation(
237 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
238 b.navNewProfileButton.startAnimation(
239 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
243 mProfileListAdapter.notifyDataSetChanged();
246 LinearLayoutManager llm = new LinearLayoutManager(this);
248 llm.setOrientation(RecyclerView.VERTICAL);
249 b.navProfileList.setLayoutManager(llm);
251 b.navProfilesStartEdit.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
252 b.navProfilesCancelEdit.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
253 b.navProfileListHeadButtons.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
254 if (drawerListener == null) {
255 drawerListener = new DrawerLayout.SimpleDrawerListener() {
257 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
258 if (slideOffset > 0.2)
262 public void onDrawerClosed(View drawerView) {
263 super.onDrawerClosed(drawerView);
264 mProfileListAdapter.setAnimationsEnabled(false);
265 mProfileListAdapter.editingProfiles.setValue(false);
266 Data.drawerOpen.setValue(false);
270 public void onDrawerOpened(View drawerView) {
271 super.onDrawerOpened(drawerView);
272 mProfileListAdapter.setAnimationsEnabled(true);
273 Data.drawerOpen.setValue(true);
277 b.drawerLayout.addDrawerListener(drawerListener);
280 Data.drawerOpen.observe(this, open -> {
282 b.drawerLayout.open();
284 b.drawerLayout.close();
287 mainModel.getUpdateError()
288 .observe(this, (error) -> {
292 Snackbar.make(b.mainPager, error, Snackbar.LENGTH_INDEFINITE)
294 mainModel.clearUpdateError();
296 Data.locale.observe(this, l -> refreshLastUpdateInfo());
297 Data.lastUpdateDate.observe(this, date -> refreshLastUpdateInfo());
298 Data.lastUpdateTransactionCount.observe(this, date -> refreshLastUpdateInfo());
299 Data.lastUpdateAccountCount.observe(this, date -> refreshLastUpdateInfo());
300 b.navAccountSummary.setOnClickListener(this::onAccountSummaryClicked);
301 b.navLatestTransactions.setOnClickListener(this::onLatestTransactionsClicked);
302 b.navPatterns.setOnClickListener(this::onPatternsClick);
304 private void onPatternsClick(View view) {
305 Intent intent = new Intent(this, TemplatesActivity.class);
306 startActivity(intent);
308 private void scheduleDataRetrievalIfStale(long lastUpdate) {
309 long now = new Date().getTime();
310 if ((lastUpdate == 0) || (now > (lastUpdate + (24 * 3600 * 1000)))) {
312 Logger.debug("db::", "WEB data never fetched. scheduling a fetch");
314 Logger.debug("db", String.format(Locale.ENGLISH,
315 "WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
316 lastUpdate / 1000f, now / 1000f));
318 mainModel.scheduleTransactionListRetrieval();
321 private void createShortcuts(List<MobileLedgerProfile> list) {
322 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
325 ShortcutManager sm = getSystemService(ShortcutManager.class);
326 List<ShortcutInfo> shortcuts = new ArrayList<>();
328 for (MobileLedgerProfile p : list) {
329 if (shortcuts.size() >= sm.getMaxShortcutCountPerActivity())
332 if (!p.isPostingPermitted())
335 final ShortcutInfo.Builder builder =
336 new ShortcutInfo.Builder(this, "new_transaction_" + p.getUuid());
337 ShortcutInfo si = builder.setShortLabel(p.getName())
338 .setIcon(Icon.createWithResource(this,
339 R.drawable.thick_plus_icon))
340 .setIntent(new Intent(Intent.ACTION_VIEW, null, this,
341 NewTransactionActivity.class).putExtra("profile_uuid",
348 sm.setDynamicShortcuts(shortcuts);
350 private void onProfileListChanged(List<MobileLedgerProfile> newList) {
351 if ((newList == null) || newList.isEmpty()) {
352 b.noProfilesLayout.setVisibility(View.VISIBLE);
353 b.mainAppLayout.setVisibility(View.GONE);
357 b.mainAppLayout.setVisibility(View.VISIBLE);
358 b.noProfilesLayout.setVisibility(View.GONE);
360 b.navProfileList.setMinimumHeight(
361 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
363 Logger.debug("profiles", "profile list changed");
364 mProfileListAdapter.notifyDataSetChanged();
366 createShortcuts(newList);
369 * called when the current profile has changed
371 private void onProfileChanged(MobileLedgerProfile profile) {
372 if (this.profile == null) {
377 if (this.profile.equals(profile))
381 boolean haveProfile = profile != null;
384 setTitle(profile.getName());
386 setTitle(R.string.app_name);
388 mainModel.setProfile(profile);
390 this.profile = profile;
392 int newProfileTheme = haveProfile ? profile.getThemeHue() : -1;
393 if (newProfileTheme != Colors.profileThemeId) {
394 Logger.debug("profiles",
395 String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
397 Colors.profileThemeId = newProfileTheme;
398 profileThemeChanged();
399 // profileThemeChanged would restart the activity, so no need to reload the
404 b.noProfilesLayout.setVisibility(haveProfile ? View.GONE : View.VISIBLE);
405 b.pagerLayout.setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
407 mProfileListAdapter.notifyDataSetChanged();
409 mainModel.clearAccounts();
410 mainModel.clearTransactions();
413 mainModel.scheduleAccountListReload();
414 Logger.debug("transactions", "requesting list reload");
415 mainModel.scheduleTransactionListReload();
417 if (profile.isPostingPermitted()) {
418 b.toolbar.setSubtitle(null);
419 b.btnAddTransaction.show();
422 b.toolbar.setSubtitle(R.string.profile_subtitle_read_only);
423 b.btnAddTransaction.hide();
427 b.toolbar.setSubtitle(null);
428 b.btnAddTransaction.hide();
431 updateLastUpdateTextFromDB();
433 private void profileThemeChanged() {
434 // un-hook all observed LiveData
435 Data.removeProfileObservers(this);
436 Data.profiles.removeObservers(this);
437 Data.lastUpdateTransactionCount.removeObservers(this);
438 Data.lastUpdateAccountCount.removeObservers(this);
439 Data.lastUpdateDate.removeObservers(this);
443 public void fabNewTransactionClicked(View view) {
444 Intent intent = new Intent(this, NewTransactionActivity.class);
445 startActivity(intent);
446 overridePendingTransition(R.anim.slide_in_up, R.anim.dummy);
448 public void markDrawerItemCurrent(int id) {
449 TextView item = b.drawerLayout.findViewById(id);
450 item.setBackgroundColor(Colors.tableRowDarkBG);
452 for (int i = 0; i < b.navActions.getChildCount(); i++) {
453 View view = b.navActions.getChildAt(i);
454 if (view.getId() != id) {
455 view.setBackgroundColor(Color.TRANSPARENT);
459 public void onAccountSummaryClicked(View view) {
460 b.drawerLayout.closeDrawers();
462 showAccountSummaryFragment();
464 private void showAccountSummaryFragment() {
465 b.mainPager.setCurrentItem(0, true);
466 mainModel.getAccountFilter()
469 public void onLatestTransactionsClicked(View view) {
470 b.drawerLayout.closeDrawers();
472 showTransactionsFragment(null);
474 public void showTransactionsFragment(String accName) {
475 mainModel.getAccountFilter()
477 b.mainPager.setCurrentItem(1, true);
479 public void showAccountTransactions(String accountName) {
480 mBackMeansToAccountList = true;
481 showTransactionsFragment(accountName);
484 public void onBackPressed() {
485 if (b.drawerLayout.isDrawerOpen(GravityCompat.START)) {
486 b.drawerLayout.closeDrawer(GravityCompat.START);
489 if (mBackMeansToAccountList && (b.mainPager.getCurrentItem() == 1)) {
490 mainModel.getAccountFilter()
492 showAccountSummaryFragment();
493 mBackMeansToAccountList = false;
496 Logger.debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
497 getSupportFragmentManager().getBackStackEntryCount()));
499 super.onBackPressed();
503 public void updateLastUpdateTextFromDB() {
507 long lastUpdate = profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
509 Logger.debug("transactions", String.format(Locale.ENGLISH, "Last update = %d", lastUpdate));
510 if (lastUpdate == 0) {
511 Data.lastUpdateDate.postValue(null);
514 Data.lastUpdateDate.postValue(new Date(lastUpdate));
517 scheduleDataRetrievalIfStale(lastUpdate);
520 private void refreshLastUpdateInfo() {
521 final int formatFlags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR |
522 DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_NUMERIC_DATE;
523 String templateForTransactions =
524 getResources().getString(R.string.transaction_count_summary);
525 String templateForAccounts = getResources().getString(R.string.account_count_summary);
526 Integer accountCount = Data.lastUpdateAccountCount.getValue();
527 Integer transactionCount = Data.lastUpdateTransactionCount.getValue();
528 Date lastUpdate = Data.lastUpdateDate.getValue();
529 if (lastUpdate == null) {
530 Data.lastTransactionsUpdateText.set("----");
531 Data.lastAccountsUpdateText.set("----");
534 Data.lastTransactionsUpdateText.set(
535 String.format(Objects.requireNonNull(Data.locale.getValue()),
536 templateForTransactions,
537 transactionCount == null ? 0 : transactionCount,
538 DateUtils.formatDateTime(this, lastUpdate.getTime(), formatFlags)));
539 Data.lastAccountsUpdateText.set(
540 String.format(Objects.requireNonNull(Data.locale.getValue()),
541 templateForAccounts, accountCount == null ? 0 : accountCount,
542 DateUtils.formatDateTime(this, lastUpdate.getTime(), formatFlags)));
545 public void onStopTransactionRefreshClick(View view) {
546 Logger.debug("interactive", "Cancelling transactions refresh");
547 mainModel.stopTransactionsRetrieval();
548 b.transactionListCancelDownload.setEnabled(false);
550 public void onRetrieveRunningChanged(Boolean running) {
552 b.transactionListCancelDownload.setEnabled(true);
553 ColorStateList csl = Colors.getColorStateList();
554 b.transactionListProgressBar.setIndeterminateTintList(csl);
555 b.transactionListProgressBar.setProgressTintList(csl);
556 b.transactionListProgressBar.setIndeterminate(true);
557 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
558 b.transactionListProgressBar.setProgress(0, false);
561 b.transactionListProgressBar.setProgress(0);
563 b.transactionProgressLayout.setVisibility(View.VISIBLE);
566 b.transactionProgressLayout.setVisibility(View.GONE);
569 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
570 if (progress.getState() == RetrieveTransactionsTask.ProgressState.FINISHED) {
571 Logger.debug("progress", "Done");
572 b.transactionProgressLayout.setVisibility(View.GONE);
574 mainModel.transactionRetrievalDone();
576 String error = progress.getError();
578 if (error.equals(RetrieveTransactionsTask.Result.ERR_JSON_PARSER_ERROR))
579 error = getResources().getString(R.string.err_json_parser_error);
581 AlertDialog.Builder builder = new AlertDialog.Builder(this);
582 builder.setMessage(error);
583 builder.setPositiveButton(R.string.btn_profile_options, (dialog, which) -> {
584 Logger.debug("error", "will start profile editor");
585 MobileLedgerProfile.startEditProfileActivity(this, profile);
596 b.transactionListCancelDownload.setEnabled(true);
597 // ColorStateList csl = Colors.getColorStateList();
598 // progressBar.setIndeterminateTintList(csl);
599 // progressBar.setProgressTintList(csl);
600 // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
601 // progressBar.setProgress(0, false);
603 // progressBar.setProgress(0);
604 b.transactionProgressLayout.setVisibility(View.VISIBLE);
606 if (progress.isIndeterminate() || (progress.getTotal() <= 0)) {
607 b.transactionListProgressBar.setIndeterminate(true);
608 Logger.debug("progress", "indeterminate");
611 if (b.transactionListProgressBar.isIndeterminate()) {
612 b.transactionListProgressBar.setIndeterminate(false);
614 // Logger.debug("progress",
615 // String.format(Locale.US, "%d/%d", progress.getProgress(), progress.getTotal
617 b.transactionListProgressBar.setMax(progress.getTotal());
618 // for some reason animation doesn't work - no progress is shown (stick at 0)
619 // on lineageOS 14.1 (Nougat, 7.1.2)
620 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
621 b.transactionListProgressBar.setProgress(progress.getProgress(), false);
623 b.transactionListProgressBar.setProgress(progress.getProgress());
626 public void fabShouldShow() {
627 if ((profile != null) && profile.isPostingPermitted() && !b.drawerLayout.isOpen())
628 b.btnAddTransaction.show();
632 public void fabHide() {
633 b.btnAddTransaction.hide();
636 public static class SectionsPagerAdapter extends FragmentStateAdapter {
638 public SectionsPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
639 super(fragmentActivity);
643 public Fragment createFragment(int position) {
645 String.format(Locale.ENGLISH, "Switching to fragment %d", position));
648 // debug("flow", "Creating account summary fragment");
649 return new AccountSummaryFragment();
651 return new TransactionListFragment();
653 throw new IllegalStateException(
654 String.format("Unexpected fragment index: " + "%d", position));
659 public int getItemCount() {