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.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.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.app.AlertDialog;
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.FragmentActivity;
45 import androidx.lifecycle.ViewModelProvider;
46 import androidx.recyclerview.widget.LinearLayoutManager;
47 import androidx.recyclerview.widget.RecyclerView;
48 import androidx.viewpager2.adapter.FragmentStateAdapter;
49 import androidx.viewpager2.widget.ViewPager2;
51 import com.google.android.material.floatingactionbutton.FloatingActionButton;
52 import com.google.android.material.snackbar.Snackbar;
54 import net.ktnx.mobileledger.R;
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.MainModel;
59 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
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.util.ArrayList;
69 import java.util.Date;
70 import java.util.List;
71 import java.util.Locale;
72 import java.util.Objects;
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";
83 private View profileListHeadMore, profileListHeadCancel, profileListHeadAddProfile;
84 private View bTransactionListCancelDownload;
85 private SectionsPagerAdapter mSectionsPagerAdapter;
86 private ViewPager2 mViewPager;
87 private FloatingActionButton fab;
88 private ProfilesRecyclerViewAdapter mProfileListAdapter;
89 private int mCurrentPage;
90 private boolean mBackMeansToAccountList = false;
91 private Toolbar mToolbar;
92 private DrawerLayout.SimpleDrawerListener drawerListener;
93 private ActionBarDrawerToggle barDrawerToggle;
94 private ViewPager2.OnPageChangeCallback pageChangeCallback;
95 private MobileLedgerProfile profile;
96 private MainModel mainModel;
98 protected void onStart() {
101 Logger.debug("MainActivity", "onStart()");
103 mViewPager.setCurrentItem(mCurrentPage, false);
106 protected void onSaveInstanceState(@NotNull Bundle outState) {
107 super.onSaveInstanceState(outState);
108 outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
109 if (mainModel.getAccountFilter()
111 outState.putString(STATE_ACC_FILTER, mainModel.getAccountFilter()
115 protected void onDestroy() {
116 mSectionsPagerAdapter = null;
117 RecyclerView root = findViewById(R.id.nav_profile_list);
119 root.setAdapter(null);
121 drawer.removeDrawerListener(drawerListener);
122 drawerListener = null;
124 drawer.removeDrawerListener(barDrawerToggle);
125 barDrawerToggle = null;
126 if (mViewPager != null)
127 mViewPager.unregisterOnPageChangeCallback(pageChangeCallback);
128 pageChangeCallback = null;
132 protected void onResume() {
137 protected void onCreate(Bundle savedInstanceState) {
138 Logger.debug("MainActivity", "onCreate()/entry");
139 super.onCreate(savedInstanceState);
140 Logger.debug("MainActivity", "onCreate()/after super");
141 setContentView(R.layout.activity_main);
143 mainModel = new ViewModelProvider(this).get(MainModel.class);
145 fab = findViewById(R.id.btn_add_transaction);
146 profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
147 profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
148 LinearLayout profileListHeadMoreAndCancel =
149 findViewById(R.id.nav_profile_list_head_buttons);
150 profileListHeadAddProfile = findViewById(R.id.nav_new_profile_button);
151 drawer = findViewById(R.id.drawer_layout);
152 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
153 mSectionsPagerAdapter = new SectionsPagerAdapter(this);
154 mViewPager = findViewById(R.id.root_frame);
156 Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
157 if (extra != null && savedInstanceState == null)
158 savedInstanceState = extra;
161 mToolbar = findViewById(R.id.toolbar);
162 setSupportActionBar(mToolbar);
164 Data.observeProfile(this, this::onProfileChanged);
166 Data.profiles.observe(this, this::onProfileListChanged);
167 Data.backgroundTaskProgress.observe(this, this::onRetrieveProgress);
168 Data.backgroundTasksRunning.observe(this, this::onRetrieveRunningChanged);
170 if (barDrawerToggle == null) {
171 barDrawerToggle = new ActionBarDrawerToggle(this, drawer, mToolbar,
172 R.string.navigation_drawer_open, R.string.navigation_drawer_close);
173 drawer.addDrawerListener(barDrawerToggle);
175 barDrawerToggle.syncState();
178 PackageInfo pi = getApplicationContext().getPackageManager()
179 .getPackageInfo(getPackageName(), 0);
180 ((TextView) findViewById(R.id.nav_upper).findViewById(
181 R.id.drawer_version_text)).setText(pi.versionName);
182 ((TextView) findViewById(R.id.no_profiles_layout).findViewById(
183 R.id.drawer_version_text)).setText(pi.versionName);
185 catch (Exception e) {
189 markDrawerItemCurrent(R.id.nav_account_summary);
191 mViewPager.setAdapter(mSectionsPagerAdapter);
193 if (pageChangeCallback == null) {
194 pageChangeCallback = new ViewPager2.OnPageChangeCallback() {
196 public void onPageSelected(int position) {
197 mCurrentPage = position;
200 markDrawerItemCurrent(R.id.nav_account_summary);
203 markDrawerItemCurrent(R.id.nav_latest_transactions);
206 Log.e("MainActivity",
207 String.format("Unexpected page index %d", position));
210 super.onPageSelected(position);
213 mViewPager.registerOnPageChangeCallback(pageChangeCallback);
217 if (savedInstanceState != null) {
218 int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
219 if (currentPage != -1) {
220 mCurrentPage = currentPage;
222 mainModel.getAccountFilter()
223 .setValue(savedInstanceState.getString(STATE_ACC_FILTER, null));
226 findViewById(R.id.btn_no_profiles_add).setOnClickListener(
227 v -> MobileLedgerProfile.startEditProfileActivity(this, null));
229 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
231 findViewById(R.id.nav_new_profile_button).setOnClickListener(
232 v -> MobileLedgerProfile.startEditProfileActivity(this, null));
234 findViewById(R.id.transaction_list_cancel_download).setOnClickListener(
235 this::onStopTransactionRefreshClick);
237 RecyclerView root = findViewById(R.id.nav_profile_list);
239 throw new RuntimeException("Can't get hold on the transaction value view");
241 if (mProfileListAdapter == null)
242 mProfileListAdapter = new ProfilesRecyclerViewAdapter();
243 root.setAdapter(mProfileListAdapter);
245 mProfileListAdapter.editingProfiles.observe(this, newValue -> {
247 profileListHeadMore.setVisibility(View.GONE);
248 profileListHeadCancel.setVisibility(View.VISIBLE);
249 profileListHeadAddProfile.setVisibility(View.VISIBLE);
250 if (drawer.isDrawerOpen(GravityCompat.START)) {
251 profileListHeadMore.startAnimation(
252 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
253 profileListHeadCancel.startAnimation(
254 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
255 profileListHeadAddProfile.startAnimation(
256 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
260 profileListHeadCancel.setVisibility(View.GONE);
261 profileListHeadMore.setVisibility(View.VISIBLE);
262 profileListHeadAddProfile.setVisibility(View.GONE);
263 if (drawer.isDrawerOpen(GravityCompat.START)) {
264 profileListHeadCancel.startAnimation(
265 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
266 profileListHeadMore.startAnimation(
267 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
268 profileListHeadAddProfile.startAnimation(
269 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
273 mProfileListAdapter.notifyDataSetChanged();
276 LinearLayoutManager llm = new LinearLayoutManager(this);
278 llm.setOrientation(RecyclerView.VERTICAL);
279 root.setLayoutManager(llm);
281 profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
282 profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
283 profileListHeadMoreAndCancel.setOnClickListener(
284 (v) -> mProfileListAdapter.flipEditingProfiles());
285 if (drawerListener == null) {
286 drawerListener = new DrawerLayout.SimpleDrawerListener() {
288 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
289 if (slideOffset > 0.2)
293 public void onDrawerClosed(View drawerView) {
294 super.onDrawerClosed(drawerView);
295 mProfileListAdapter.setAnimationsEnabled(false);
296 mProfileListAdapter.editingProfiles.setValue(false);
297 Data.drawerOpen.setValue(false);
301 public void onDrawerOpened(View drawerView) {
302 super.onDrawerOpened(drawerView);
303 mProfileListAdapter.setAnimationsEnabled(true);
304 Data.drawerOpen.setValue(true);
308 drawer.addDrawerListener(drawerListener);
311 Data.drawerOpen.observe(this, open -> {
318 mainModel.getUpdateError()
319 .observe(this, (error) -> {
323 Snackbar.make(mViewPager, error, Snackbar.LENGTH_LONG)
325 mainModel.clearUpdateError();
327 Data.locale.observe(this, l -> refreshLastUpdateInfo());
328 Data.lastUpdateDate.observe(this, date -> refreshLastUpdateInfo());
329 Data.lastUpdateTransactionCount.observe(this, date -> refreshLastUpdateInfo());
330 Data.lastUpdateAccountCount.observe(this, date -> refreshLastUpdateInfo());
332 private void scheduleDataRetrievalIfStale(long lastUpdate) {
333 long now = new Date().getTime();
334 if ((lastUpdate == 0) || (now > (lastUpdate + (24 * 3600 * 1000)))) {
336 Logger.debug("db::", "WEB data never fetched. scheduling a fetch");
338 Logger.debug("db", String.format(Locale.ENGLISH,
339 "WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
340 lastUpdate / 1000f, now / 1000f));
342 mainModel.scheduleTransactionListRetrieval();
345 private void createShortcuts(List<MobileLedgerProfile> list) {
346 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
349 ShortcutManager sm = getSystemService(ShortcutManager.class);
350 List<ShortcutInfo> shortcuts = new ArrayList<>();
352 for (MobileLedgerProfile p : list) {
353 if (shortcuts.size() >= sm.getMaxShortcutCountPerActivity())
356 if (!p.isPostingPermitted())
359 final ShortcutInfo.Builder builder =
360 new ShortcutInfo.Builder(this, "new_transaction_" + p.getUuid());
361 ShortcutInfo si = builder.setShortLabel(p.getName())
362 .setIcon(Icon.createWithResource(this,
363 R.drawable.thick_plus_icon))
364 .setIntent(new Intent(Intent.ACTION_VIEW, null, this,
365 NewTransactionActivity.class).putExtra("profile_uuid",
372 sm.setDynamicShortcuts(shortcuts);
374 private void onProfileListChanged(List<MobileLedgerProfile> newList) {
375 if ((newList == null) || newList.isEmpty()) {
376 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
377 findViewById(R.id.main_app_layout).setVisibility(View.GONE);
381 findViewById(R.id.main_app_layout).setVisibility(View.VISIBLE);
382 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
384 findViewById(R.id.nav_profile_list).setMinimumHeight(
385 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
387 Logger.debug("profiles", "profile list changed");
388 mProfileListAdapter.notifyDataSetChanged();
390 createShortcuts(newList);
393 * called when the current profile has changed
395 private void onProfileChanged(MobileLedgerProfile profile) {
396 if (this.profile == null) {
401 if (this.profile.equals(profile))
405 boolean haveProfile = profile != null;
408 setTitle(profile.getName());
410 setTitle(R.string.app_name);
412 mainModel.setProfile(profile);
414 this.profile = profile;
416 int newProfileTheme = haveProfile ? profile.getThemeHue() : -1;
417 if (newProfileTheme != Colors.profileThemeId) {
418 Logger.debug("profiles",
419 String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
421 Colors.profileThemeId = newProfileTheme;
422 profileThemeChanged();
423 // profileThemeChanged would restart the activity, so no need to reload the
428 findViewById(R.id.no_profiles_layout).setVisibility(haveProfile ? View.GONE : View.VISIBLE);
429 findViewById(R.id.pager_layout).setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
431 mProfileListAdapter.notifyDataSetChanged();
433 mainModel.clearAccounts();
434 mainModel.clearTransactions();
437 mainModel.scheduleAccountListReload();
438 Logger.debug("transactions", "requesting list reload");
439 mainModel.scheduleTransactionListReload();
441 if (profile.isPostingPermitted()) {
442 mToolbar.setSubtitle(null);
446 mToolbar.setSubtitle(R.string.profile_subtitle_read_only);
451 mToolbar.setSubtitle(null);
455 updateLastUpdateTextFromDB();
457 private void profileThemeChanged() {
458 // un-hook all observed LiveData
459 Data.removeProfileObservers(this);
460 Data.profiles.removeObservers(this);
461 Data.lastUpdateTransactionCount.removeObservers(this);
462 Data.lastUpdateAccountCount.removeObservers(this);
463 Data.lastUpdateDate.removeObservers(this);
467 public void fabNewTransactionClicked(View view) {
468 Intent intent = new Intent(this, NewTransactionActivity.class);
469 startActivity(intent);
470 overridePendingTransition(R.anim.slide_in_up, R.anim.dummy);
472 public void markDrawerItemCurrent(int id) {
473 TextView item = drawer.findViewById(id);
474 item.setBackgroundColor(Colors.tableRowDarkBG);
476 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
477 for (int i = 0; i < actions.getChildCount(); i++) {
478 View view = actions.getChildAt(i);
479 if (view.getId() != id) {
480 view.setBackgroundColor(Color.TRANSPARENT);
484 public void onAccountSummaryClicked(View view) {
485 drawer.closeDrawers();
487 showAccountSummaryFragment();
489 private void showAccountSummaryFragment() {
490 mViewPager.setCurrentItem(0, true);
491 mainModel.getAccountFilter()
494 public void onLatestTransactionsClicked(View view) {
495 drawer.closeDrawers();
497 showTransactionsFragment(null);
499 public void showTransactionsFragment(String accName) {
500 mainModel.getAccountFilter()
502 mViewPager.setCurrentItem(1, true);
504 public void showAccountTransactions(String accountName) {
505 mBackMeansToAccountList = true;
506 showTransactionsFragment(accountName);
509 public void onBackPressed() {
510 DrawerLayout drawer = findViewById(R.id.drawer_layout);
511 if (drawer.isDrawerOpen(GravityCompat.START)) {
512 drawer.closeDrawer(GravityCompat.START);
515 if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
516 mainModel.getAccountFilter()
518 showAccountSummaryFragment();
519 mBackMeansToAccountList = false;
522 Logger.debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
523 getSupportFragmentManager().getBackStackEntryCount()));
525 super.onBackPressed();
529 public void updateLastUpdateTextFromDB() {
533 long lastUpdate = profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
535 Logger.debug("transactions", String.format(Locale.ENGLISH, "Last update = %d", lastUpdate));
536 if (lastUpdate == 0) {
537 Data.lastUpdateDate.postValue(null);
540 Data.lastUpdateDate.postValue(new Date(lastUpdate));
543 scheduleDataRetrievalIfStale(lastUpdate);
546 private void refreshLastUpdateInfo() {
547 final int formatFlags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR |
548 DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_NUMERIC_DATE;
549 String templateForTransactions =
550 getResources().getString(R.string.transaction_count_summary);
551 String templateForAccounts = getResources().getString(R.string.account_count_summary);
552 Integer accountCount = Data.lastUpdateAccountCount.getValue();
553 Integer transactionCount = Data.lastUpdateTransactionCount.getValue();
554 Date lastUpdate = Data.lastUpdateDate.getValue();
555 if (lastUpdate == null) {
556 Data.lastTransactionsUpdateText.set("----");
557 Data.lastAccountsUpdateText.set("----");
560 Data.lastTransactionsUpdateText.set(
561 String.format(Objects.requireNonNull(Data.locale.getValue()),
562 templateForTransactions,
563 transactionCount == null ? 0 : transactionCount,
564 DateUtils.formatDateTime(this, lastUpdate.getTime(), formatFlags)));
565 Data.lastAccountsUpdateText.set(
566 String.format(Objects.requireNonNull(Data.locale.getValue()),
567 templateForAccounts, accountCount == null ? 0 : accountCount,
568 DateUtils.formatDateTime(this, lastUpdate.getTime(), formatFlags)));
571 public void onStopTransactionRefreshClick(View view) {
572 Logger.debug("interactive", "Cancelling transactions refresh");
573 mainModel.stopTransactionsRetrieval();
574 bTransactionListCancelDownload.setEnabled(false);
576 public void onRetrieveRunningChanged(Boolean running) {
577 final View progressLayout = findViewById(R.id.transaction_progress_layout);
579 ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
580 bTransactionListCancelDownload.setEnabled(true);
581 ColorStateList csl = Colors.getColorStateList();
582 progressBar.setIndeterminateTintList(csl);
583 progressBar.setProgressTintList(csl);
584 progressBar.setIndeterminate(true);
585 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
586 progressBar.setProgress(0, false);
589 progressBar.setProgress(0);
591 progressLayout.setVisibility(View.VISIBLE);
594 progressLayout.setVisibility(View.GONE);
597 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
598 ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
600 if (progress.getState() == RetrieveTransactionsTask.ProgressState.FINISHED) {
601 Logger.debug("progress", "Done");
602 findViewById(R.id.transaction_progress_layout).setVisibility(View.GONE);
604 mainModel.transactionRetrievalDone();
606 String error = progress.getError();
608 if (error.equals(RetrieveTransactionsTask.Result.ERR_JSON_PARSER_ERROR))
609 error = getResources().getString(R.string.err_json_parser_error);
611 AlertDialog.Builder builder = new AlertDialog.Builder(this);
612 builder.setMessage(error);
613 builder.setPositiveButton(R.string.btn_profile_options, (dialog, which) -> {
614 Logger.debug("error", "will start profile editor");
615 MobileLedgerProfile.startEditProfileActivity(this, profile);
626 bTransactionListCancelDownload.setEnabled(true);
627 // ColorStateList csl = Colors.getColorStateList();
628 // progressBar.setIndeterminateTintList(csl);
629 // progressBar.setProgressTintList(csl);
630 // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
631 // progressBar.setProgress(0, false);
633 // progressBar.setProgress(0);
634 findViewById(R.id.transaction_progress_layout).setVisibility(View.VISIBLE);
636 if (progress.isIndeterminate() || (progress.getTotal() <= 0)) {
637 progressBar.setIndeterminate(true);
638 Logger.debug("progress", "indeterminate");
641 if (progressBar.isIndeterminate()) {
642 progressBar.setIndeterminate(false);
644 // Logger.debug("progress",
645 // String.format(Locale.US, "%d/%d", progress.getProgress(), progress.getTotal
647 progressBar.setMax(progress.getTotal());
648 // for some reason animation doesn't work - no progress is shown (stick at 0)
649 // on lineageOS 14.1 (Nougat, 7.1.2)
650 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
651 progressBar.setProgress(progress.getProgress(), false);
653 progressBar.setProgress(progress.getProgress());
656 public void fabShouldShow() {
657 if ((profile != null) && profile.isPostingPermitted() && !drawer.isOpen())
662 public void fabHide() {
666 public static class SectionsPagerAdapter extends FragmentStateAdapter {
668 public SectionsPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
669 super(fragmentActivity);
673 public Fragment createFragment(int position) {
675 String.format(Locale.ENGLISH, "Switching to fragment %d", position));
678 // debug("flow", "Creating account summary fragment");
679 return new AccountSummaryFragment();
681 return new TransactionListFragment();
683 throw new IllegalStateException(
684 String.format("Unexpected fragment index: " + "%d", position));
689 public int getItemCount() {