]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
asynchronous profile initialisation
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / MainActivity.java
1 /*
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.ktnx.mobileledger.ui.activity;
19
20 import android.content.Context;
21 import android.content.Intent;
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.Build;
29 import android.os.Bundle;
30 import android.text.format.DateUtils;
31 import android.util.Log;
32 import android.view.View;
33 import android.view.animation.AnimationUtils;
34 import android.widget.TextView;
35
36 import androidx.annotation.NonNull;
37 import androidx.appcompat.app.ActionBarDrawerToggle;
38 import androidx.appcompat.app.AlertDialog;
39 import androidx.core.view.GravityCompat;
40 import androidx.drawerlayout.widget.DrawerLayout;
41 import androidx.fragment.app.Fragment;
42 import androidx.fragment.app.FragmentActivity;
43 import androidx.lifecycle.ViewModelProvider;
44 import androidx.recyclerview.widget.LinearLayoutManager;
45 import androidx.recyclerview.widget.RecyclerView;
46 import androidx.viewpager2.adapter.FragmentStateAdapter;
47 import androidx.viewpager2.widget.ViewPager2;
48
49 import com.google.android.material.snackbar.Snackbar;
50
51 import net.ktnx.mobileledger.R;
52 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
53 import net.ktnx.mobileledger.databinding.ActivityMainBinding;
54 import net.ktnx.mobileledger.model.Data;
55 import net.ktnx.mobileledger.model.MobileLedgerProfile;
56 import net.ktnx.mobileledger.ui.FabManager;
57 import net.ktnx.mobileledger.ui.MainModel;
58 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
59 import net.ktnx.mobileledger.ui.new_transaction.NewTransactionActivity;
60 import net.ktnx.mobileledger.ui.profiles.ProfilesRecyclerViewAdapter;
61 import net.ktnx.mobileledger.ui.templates.TemplatesActivity;
62 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
63 import net.ktnx.mobileledger.utils.Colors;
64 import net.ktnx.mobileledger.utils.Logger;
65 import net.ktnx.mobileledger.utils.MLDB;
66
67 import org.jetbrains.annotations.NotNull;
68
69 import java.util.ArrayList;
70 import java.util.Date;
71 import java.util.List;
72 import java.util.Locale;
73 import java.util.Objects;
74
75 /*
76  * TODO: reports
77  *  */
78
79 public class MainActivity extends ProfileThemedActivity implements FabManager.FabHandler {
80     public static final String STATE_CURRENT_PAGE = "current_page";
81     public static final String BUNDLE_SAVED_STATE = "bundle_savedState";
82     public static final String STATE_ACC_FILTER = "account_filter";
83     private static final boolean FAB_HIDDEN = false;
84     private static final boolean FAB_SHOWN = true;
85     private SectionsPagerAdapter mSectionsPagerAdapter;
86     private ProfilesRecyclerViewAdapter mProfileListAdapter;
87     private int mCurrentPage;
88     private boolean mBackMeansToAccountList = false;
89     private DrawerLayout.SimpleDrawerListener drawerListener;
90     private ActionBarDrawerToggle barDrawerToggle;
91     private ViewPager2.OnPageChangeCallback pageChangeCallback;
92     private MobileLedgerProfile profile;
93     private MainModel mainModel;
94     private ActivityMainBinding b;
95     private int fabVerticalOffset;
96     private FabManager fabManager;
97     @Override
98     protected void onStart() {
99         super.onStart();
100
101         Logger.debug("MainActivity", "onStart()");
102
103         b.mainPager.setCurrentItem(mCurrentPage, false);
104     }
105     @Override
106     protected void onSaveInstanceState(@NotNull Bundle outState) {
107         super.onSaveInstanceState(outState);
108         outState.putInt(STATE_CURRENT_PAGE, b.mainPager.getCurrentItem());
109         if (mainModel.getAccountFilter()
110                      .getValue() != null)
111             outState.putString(STATE_ACC_FILTER, mainModel.getAccountFilter()
112                                                           .getValue());
113     }
114     @Override
115     protected void onDestroy() {
116         mSectionsPagerAdapter = null;
117         b.navProfileList.setAdapter(null);
118         b.drawerLayout.removeDrawerListener(drawerListener);
119         drawerListener = null;
120         b.drawerLayout.removeDrawerListener(barDrawerToggle);
121         barDrawerToggle = null;
122         b.mainPager.unregisterOnPageChangeCallback(pageChangeCallback);
123         pageChangeCallback = null;
124         super.onDestroy();
125     }
126     @Override
127     protected void onResume() {
128         super.onResume();
129         fabShouldShow();
130     }
131     @Override
132     protected void onCreate(Bundle savedInstanceState) {
133         Logger.debug("MainActivity", "onCreate()/entry");
134         super.onCreate(savedInstanceState);
135         Logger.debug("MainActivity", "onCreate()/after super");
136         b = ActivityMainBinding.inflate(getLayoutInflater());
137         setContentView(b.getRoot());
138
139         mainModel = new ViewModelProvider(this).get(MainModel.class);
140
141         mSectionsPagerAdapter = new SectionsPagerAdapter(this);
142
143         Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
144         if (extra != null && savedInstanceState == null)
145             savedInstanceState = extra;
146
147
148         setSupportActionBar(b.toolbar);
149
150         Data.observeProfile(this, this::onProfileChanged);
151
152         Data.profiles.observe(this, this::onProfileListChanged);
153         Data.backgroundTaskProgress.observe(this, this::onRetrieveProgress);
154         Data.backgroundTasksRunning.observe(this, this::onRetrieveRunningChanged);
155
156         if (barDrawerToggle == null) {
157             barDrawerToggle = new ActionBarDrawerToggle(this, b.drawerLayout, b.toolbar,
158                     R.string.navigation_drawer_open, R.string.navigation_drawer_close);
159             b.drawerLayout.addDrawerListener(barDrawerToggle);
160         }
161         barDrawerToggle.syncState();
162
163         try {
164             PackageInfo pi = getApplicationContext().getPackageManager()
165                                                     .getPackageInfo(getPackageName(), 0);
166             ((TextView) b.navUpper.findViewById(R.id.drawer_version_text)).setText(pi.versionName);
167             ((TextView) b.noProfilesLayout.findViewById(R.id.drawer_version_text)).setText(
168                     pi.versionName);
169         }
170         catch (Exception e) {
171             e.printStackTrace();
172         }
173
174         markDrawerItemCurrent(R.id.nav_account_summary);
175
176         b.mainPager.setAdapter(mSectionsPagerAdapter);
177
178         if (pageChangeCallback == null) {
179             pageChangeCallback = new ViewPager2.OnPageChangeCallback() {
180                 @Override
181                 public void onPageSelected(int position) {
182                     mCurrentPage = position;
183                     switch (position) {
184                         case 0:
185                             markDrawerItemCurrent(R.id.nav_account_summary);
186                             break;
187                         case 1:
188                             markDrawerItemCurrent(R.id.nav_latest_transactions);
189                             break;
190                         default:
191                             Log.e("MainActivity",
192                                     String.format("Unexpected page index %d", position));
193                     }
194
195                     super.onPageSelected(position);
196                 }
197             };
198             b.mainPager.registerOnPageChangeCallback(pageChangeCallback);
199         }
200
201         mCurrentPage = 0;
202         if (savedInstanceState != null) {
203             int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
204             if (currentPage != -1) {
205                 mCurrentPage = currentPage;
206             }
207             mainModel.getAccountFilter()
208                      .setValue(savedInstanceState.getString(STATE_ACC_FILTER, null));
209         }
210
211         b.btnNoProfilesAdd.setOnClickListener(
212                 v -> MobileLedgerProfile.startEditProfileActivity(this, null));
213
214         b.btnAddTransaction.setOnClickListener(this::fabNewTransactionClicked);
215
216         b.navNewProfileButton.setOnClickListener(
217                 v -> MobileLedgerProfile.startEditProfileActivity(this, null));
218
219         b.transactionListCancelDownload.setOnClickListener(this::onStopTransactionRefreshClick);
220
221         if (mProfileListAdapter == null)
222             mProfileListAdapter = new ProfilesRecyclerViewAdapter();
223         b.navProfileList.setAdapter(mProfileListAdapter);
224
225         mProfileListAdapter.editingProfiles.observe(this, newValue -> {
226             if (newValue) {
227                 b.navProfilesStartEdit.setVisibility(View.GONE);
228                 b.navProfilesCancelEdit.setVisibility(View.VISIBLE);
229                 b.navNewProfileButton.setVisibility(View.VISIBLE);
230                 if (b.drawerLayout.isDrawerOpen(GravityCompat.START)) {
231                     b.navProfilesStartEdit.startAnimation(
232                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
233                     b.navProfilesCancelEdit.startAnimation(
234                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
235                     b.navNewProfileButton.startAnimation(
236                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
237                 }
238             }
239             else {
240                 b.navProfilesCancelEdit.setVisibility(View.GONE);
241                 b.navProfilesStartEdit.setVisibility(View.VISIBLE);
242                 b.navNewProfileButton.setVisibility(View.GONE);
243                 if (b.drawerLayout.isDrawerOpen(GravityCompat.START)) {
244                     b.navProfilesCancelEdit.startAnimation(
245                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
246                     b.navProfilesStartEdit.startAnimation(
247                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
248                     b.navNewProfileButton.startAnimation(
249                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
250                 }
251             }
252
253             mProfileListAdapter.notifyDataSetChanged();
254         });
255
256         fabManager = new FabManager(b.btnAddTransaction);
257
258         LinearLayoutManager llm = new LinearLayoutManager(this);
259
260         llm.setOrientation(RecyclerView.VERTICAL);
261         b.navProfileList.setLayoutManager(llm);
262
263         b.navProfilesStartEdit.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
264         b.navProfilesCancelEdit.setOnClickListener(
265                 (v) -> mProfileListAdapter.flipEditingProfiles());
266         b.navProfileListHeadButtons.setOnClickListener(
267                 (v) -> mProfileListAdapter.flipEditingProfiles());
268         if (drawerListener == null) {
269             drawerListener = new DrawerLayout.SimpleDrawerListener() {
270                 @Override
271                 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
272                     if (slideOffset > 0.2)
273                         fabManager.hideFab();
274                 }
275                 @Override
276                 public void onDrawerClosed(View drawerView) {
277                     super.onDrawerClosed(drawerView);
278                     mProfileListAdapter.setAnimationsEnabled(false);
279                     mProfileListAdapter.editingProfiles.setValue(false);
280                     Data.drawerOpen.setValue(false);
281                     fabShouldShow();
282                 }
283                 @Override
284                 public void onDrawerOpened(View drawerView) {
285                     super.onDrawerOpened(drawerView);
286                     mProfileListAdapter.setAnimationsEnabled(true);
287                     Data.drawerOpen.setValue(true);
288                     fabManager.hideFab();
289                 }
290             };
291             b.drawerLayout.addDrawerListener(drawerListener);
292         }
293
294         Data.drawerOpen.observe(this, open -> {
295             if (open)
296                 b.drawerLayout.open();
297             else
298                 b.drawerLayout.close();
299         });
300
301         mainModel.getUpdateError()
302                  .observe(this, (error) -> {
303                      if (error == null)
304                          return;
305
306                      Snackbar.make(b.mainPager, error, Snackbar.LENGTH_INDEFINITE)
307                              .show();
308                      mainModel.clearUpdateError();
309                  });
310         Data.locale.observe(this, l -> refreshLastUpdateInfo());
311         Data.lastUpdateDate.observe(this, date -> refreshLastUpdateInfo());
312         Data.lastUpdateTransactionCount.observe(this, date -> refreshLastUpdateInfo());
313         Data.lastUpdateAccountCount.observe(this, date -> refreshLastUpdateInfo());
314         b.navAccountSummary.setOnClickListener(this::onAccountSummaryClicked);
315         b.navLatestTransactions.setOnClickListener(this::onLatestTransactionsClicked);
316         b.navPatterns.setOnClickListener(this::onPatternsClick);
317     }
318     private void onPatternsClick(View view) {
319         Intent intent = new Intent(this, TemplatesActivity.class);
320         startActivity(intent);
321     }
322     private void scheduleDataRetrievalIfStale(long lastUpdate) {
323         long now = new Date().getTime();
324         if ((lastUpdate == 0) || (now > (lastUpdate + (24 * 3600 * 1000)))) {
325             if (lastUpdate == 0)
326                 Logger.debug("db::", "WEB data never fetched. scheduling a fetch");
327             else
328                 Logger.debug("db", String.format(Locale.ENGLISH,
329                         "WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
330                         lastUpdate / 1000f, now / 1000f));
331
332             mainModel.scheduleTransactionListRetrieval();
333         }
334     }
335     private void createShortcuts(List<MobileLedgerProfile> list) {
336         if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
337             return;
338
339         ShortcutManager sm = getSystemService(ShortcutManager.class);
340         List<ShortcutInfo> shortcuts = new ArrayList<>();
341         int i = 0;
342         for (MobileLedgerProfile p : list) {
343             if (shortcuts.size() >= sm.getMaxShortcutCountPerActivity())
344                 break;
345
346             if (!p.isPostingPermitted())
347                 continue;
348
349             final ShortcutInfo.Builder builder =
350                     new ShortcutInfo.Builder(this, "new_transaction_" + p.getId());
351             ShortcutInfo si = builder.setShortLabel(p.getName())
352                                      .setIcon(Icon.createWithResource(this,
353                                              R.drawable.thick_plus_icon))
354                                      .setIntent(new Intent(Intent.ACTION_VIEW, null, this,
355                                              NewTransactionActivity.class).putExtra(
356                                              ProfileThemedActivity.PARAM_PROFILE_ID, p.getId())
357                                                                           .putExtra(
358                                                                                   ProfileThemedActivity.PARAM_THEME,
359                                                                                   p.getThemeHue()))
360                                      .setRank(i)
361                                      .build();
362             shortcuts.add(si);
363             i++;
364         }
365         sm.setDynamicShortcuts(shortcuts);
366     }
367     private void onProfileListChanged(List<MobileLedgerProfile> newList) {
368         if ((newList == null) || newList.isEmpty()) {
369             b.noProfilesLayout.setVisibility(View.VISIBLE);
370             b.mainAppLayout.setVisibility(View.GONE);
371             return;
372         }
373
374         b.mainAppLayout.setVisibility(View.VISIBLE);
375         b.noProfilesLayout.setVisibility(View.GONE);
376
377         b.navProfileList.setMinimumHeight(
378                 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
379
380         Logger.debug("profiles", "profile list changed");
381         mProfileListAdapter.notifyDataSetChanged();
382
383         createShortcuts(newList);
384     }
385     /**
386      * called when the current profile has changed
387      */
388     private void onProfileChanged(MobileLedgerProfile profile) {
389         if (this.profile == null) {
390             if (profile == null)
391                 return;
392         }
393         else {
394             if (this.profile.equals(profile))
395                 return;
396         }
397
398         boolean haveProfile = profile != null;
399
400         if (haveProfile)
401             setTitle(profile.getName());
402         else
403             setTitle(R.string.app_name);
404
405         mainModel.setProfile(profile);
406
407         this.profile = profile;
408
409         int newProfileTheme = haveProfile ? profile.getThemeHue() : -1;
410         if (newProfileTheme != Colors.profileThemeId) {
411             Logger.debug("profiles",
412                     String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
413                             newProfileTheme));
414             Colors.profileThemeId = newProfileTheme;
415             profileThemeChanged();
416             // profileThemeChanged would restart the activity, so no need to reload the
417             // data sets below
418             return;
419         }
420
421         b.noProfilesLayout.setVisibility(haveProfile ? View.GONE : View.VISIBLE);
422         b.pagerLayout.setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
423
424         mProfileListAdapter.notifyDataSetChanged();
425
426         mainModel.clearAccounts();
427         mainModel.clearTransactions();
428
429         if (haveProfile) {
430             Logger.debug("transactions", "requesting list reload");
431             mainModel.scheduleTransactionListReload();
432
433             if (profile.isPostingPermitted()) {
434                 b.toolbar.setSubtitle(null);
435                 b.btnAddTransaction.show();
436             }
437             else {
438                 b.toolbar.setSubtitle(R.string.profile_subtitle_read_only);
439                 b.btnAddTransaction.hide();
440             }
441         }
442         else {
443             b.toolbar.setSubtitle(null);
444             b.btnAddTransaction.hide();
445         }
446
447         updateLastUpdateTextFromDB();
448     }
449     private void profileThemeChanged() {
450         // un-hook all observed LiveData
451         Data.removeProfileObservers(this);
452         Data.profiles.removeObservers(this);
453         Data.lastUpdateTransactionCount.removeObservers(this);
454         Data.lastUpdateAccountCount.removeObservers(this);
455         Data.lastUpdateDate.removeObservers(this);
456
457         Logger.debug("MainActivity", "profileThemeChanged(): recreating activity");
458         recreate();
459     }
460     public void fabNewTransactionClicked(View view) {
461         Intent intent = new Intent(this, NewTransactionActivity.class);
462         intent.putExtra(ProfileThemedActivity.PARAM_PROFILE_ID, profile.getId());
463         intent.putExtra(ProfileThemedActivity.PARAM_THEME, profile.getThemeHue());
464         startActivity(intent);
465         overridePendingTransition(R.anim.slide_in_up, R.anim.dummy);
466     }
467     public void markDrawerItemCurrent(int id) {
468         TextView item = b.drawerLayout.findViewById(id);
469         item.setBackgroundColor(Colors.tableRowDarkBG);
470
471         for (int i = 0; i < b.navActions.getChildCount(); i++) {
472             View view = b.navActions.getChildAt(i);
473             if (view.getId() != id) {
474                 view.setBackgroundColor(Color.TRANSPARENT);
475             }
476         }
477     }
478     public void onAccountSummaryClicked(View view) {
479         b.drawerLayout.closeDrawers();
480
481         showAccountSummaryFragment();
482     }
483     private void showAccountSummaryFragment() {
484         b.mainPager.setCurrentItem(0, true);
485         mainModel.getAccountFilter()
486                  .setValue(null);
487     }
488     public void onLatestTransactionsClicked(View view) {
489         b.drawerLayout.closeDrawers();
490
491         showTransactionsFragment(null);
492     }
493     public void showTransactionsFragment(String accName) {
494         mainModel.getAccountFilter()
495                  .setValue(accName);
496         b.mainPager.setCurrentItem(1, true);
497     }
498     public void showAccountTransactions(String accountName) {
499         mBackMeansToAccountList = true;
500         showTransactionsFragment(accountName);
501     }
502     @Override
503     public void onBackPressed() {
504         if (b.drawerLayout.isDrawerOpen(GravityCompat.START)) {
505             b.drawerLayout.closeDrawer(GravityCompat.START);
506         }
507         else {
508             if (mBackMeansToAccountList && (b.mainPager.getCurrentItem() == 1)) {
509                 mainModel.getAccountFilter()
510                          .setValue(null);
511                 showAccountSummaryFragment();
512                 mBackMeansToAccountList = false;
513             }
514             else {
515                 Logger.debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
516                         getSupportFragmentManager().getBackStackEntryCount()));
517
518                 super.onBackPressed();
519             }
520         }
521     }
522     public void updateLastUpdateTextFromDB() {
523         if (profile == null)
524             return;
525
526         long lastUpdate = profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
527
528         Logger.debug("transactions", String.format(Locale.ENGLISH, "Last update = %d", lastUpdate));
529         if (lastUpdate == 0) {
530             Data.lastUpdateDate.postValue(null);
531         }
532         else {
533             Data.lastUpdateDate.postValue(new Date(lastUpdate));
534         }
535
536         scheduleDataRetrievalIfStale(lastUpdate);
537
538     }
539     private void refreshLastUpdateInfo() {
540         final int formatFlags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR |
541                                 DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_NUMERIC_DATE;
542         String templateForTransactions =
543                 getResources().getString(R.string.transaction_count_summary);
544         String templateForAccounts = getResources().getString(R.string.account_count_summary);
545         Integer accountCount = Data.lastUpdateAccountCount.getValue();
546         Integer transactionCount = Data.lastUpdateTransactionCount.getValue();
547         Date lastUpdate = Data.lastUpdateDate.getValue();
548         if (lastUpdate == null) {
549             Data.lastTransactionsUpdateText.setValue("----");
550             Data.lastAccountsUpdateText.setValue("----");
551         }
552         else {
553             Data.lastTransactionsUpdateText.setValue(
554                     String.format(Objects.requireNonNull(Data.locale.getValue()),
555                             templateForTransactions,
556                             transactionCount == null ? 0 : transactionCount,
557                             DateUtils.formatDateTime(this, lastUpdate.getTime(), formatFlags)));
558             Data.lastAccountsUpdateText.setValue(
559                     String.format(Objects.requireNonNull(Data.locale.getValue()),
560                             templateForAccounts, accountCount == null ? 0 : accountCount,
561                             DateUtils.formatDateTime(this, lastUpdate.getTime(), formatFlags)));
562         }
563     }
564     public void onStopTransactionRefreshClick(View view) {
565         Logger.debug("interactive", "Cancelling transactions refresh");
566         mainModel.stopTransactionsRetrieval();
567         b.transactionListCancelDownload.setEnabled(false);
568     }
569     public void onRetrieveRunningChanged(Boolean running) {
570         if (running) {
571             b.transactionListCancelDownload.setEnabled(true);
572             ColorStateList csl = Colors.getColorStateList();
573             b.transactionListProgressBar.setIndeterminateTintList(csl);
574             b.transactionListProgressBar.setProgressTintList(csl);
575             b.transactionListProgressBar.setIndeterminate(true);
576             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
577                 b.transactionListProgressBar.setProgress(0, false);
578             }
579             else {
580                 b.transactionListProgressBar.setProgress(0);
581             }
582             b.transactionProgressLayout.setVisibility(View.VISIBLE);
583         }
584         else {
585             b.transactionProgressLayout.setVisibility(View.GONE);
586         }
587     }
588     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
589         if (progress.getState() == RetrieveTransactionsTask.ProgressState.FINISHED) {
590             Logger.debug("progress", "Done");
591             b.transactionProgressLayout.setVisibility(View.GONE);
592
593             mainModel.transactionRetrievalDone();
594
595             String error = progress.getError();
596             if (error != null) {
597                 if (error.equals(RetrieveTransactionsTask.Result.ERR_JSON_PARSER_ERROR))
598                     error = getResources().getString(R.string.err_json_parser_error);
599
600                 AlertDialog.Builder builder = new AlertDialog.Builder(this);
601                 builder.setMessage(error);
602                 builder.setPositiveButton(R.string.btn_profile_options, (dialog, which) -> {
603                     Logger.debug("error", "will start profile editor");
604                     MobileLedgerProfile.startEditProfileActivity(this, profile);
605                 });
606                 builder.create()
607                        .show();
608                 return;
609             }
610
611             return;
612         }
613
614
615         b.transactionListCancelDownload.setEnabled(true);
616 //        ColorStateList csl = Colors.getColorStateList();
617 //        progressBar.setIndeterminateTintList(csl);
618 //        progressBar.setProgressTintList(csl);
619 //        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
620 //            progressBar.setProgress(0, false);
621 //        else
622 //            progressBar.setProgress(0);
623         b.transactionProgressLayout.setVisibility(View.VISIBLE);
624
625         if (progress.isIndeterminate() || (progress.getTotal() <= 0)) {
626             b.transactionListProgressBar.setIndeterminate(true);
627             Logger.debug("progress", "indeterminate");
628         }
629         else {
630             if (b.transactionListProgressBar.isIndeterminate()) {
631                 b.transactionListProgressBar.setIndeterminate(false);
632             }
633 //            Logger.debug("progress",
634 //                    String.format(Locale.US, "%d/%d", progress.getProgress(), progress.getTotal
635 //                    ()));
636             b.transactionListProgressBar.setMax(progress.getTotal());
637             // for some reason animation doesn't work - no progress is shown (stick at 0)
638             // on lineageOS 14.1 (Nougat, 7.1.2)
639             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
640                 b.transactionListProgressBar.setProgress(progress.getProgress(), false);
641             else
642                 b.transactionListProgressBar.setProgress(progress.getProgress());
643         }
644     }
645     public void fabShouldShow() {
646         if ((profile != null) && profile.isPostingPermitted() && !b.drawerLayout.isOpen())
647             fabManager.showFab();
648     }
649     @Override
650     public Context getContext() {
651         return this;
652     }
653     @Override
654     public void showManagedFab() {
655         fabShouldShow();
656     }
657     @Override
658     public void hideManagedFab() {
659         fabManager.hideFab();
660     }
661     public static class SectionsPagerAdapter extends FragmentStateAdapter {
662
663         public SectionsPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
664             super(fragmentActivity);
665         }
666         @NotNull
667         @Override
668         public Fragment createFragment(int position) {
669             Logger.debug("main",
670                     String.format(Locale.ENGLISH, "Switching to fragment %d", position));
671             switch (position) {
672                 case 0:
673 //                    debug("flow", "Creating account summary fragment");
674                     return new AccountSummaryFragment();
675                 case 1:
676                     return new TransactionListFragment();
677                 default:
678                     throw new IllegalStateException(
679                             String.format("Unexpected fragment index: " + "%d", position));
680             }
681         }
682
683         @Override
684         public int getItemCount() {
685             return 2;
686         }
687     }
688 }