]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
rename patterns to templates
[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.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;
34
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;
47
48 import com.google.android.material.snackbar.Snackbar;
49
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;
64
65 import org.jetbrains.annotations.NotNull;
66
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;
72
73 /*
74  * TODO: reports
75  *  */
76
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;
91     @Override
92     protected void onStart() {
93         super.onStart();
94
95         Logger.debug("MainActivity", "onStart()");
96
97         b.mainPager.setCurrentItem(mCurrentPage, false);
98     }
99     @Override
100     protected void onSaveInstanceState(@NotNull Bundle outState) {
101         super.onSaveInstanceState(outState);
102         outState.putInt(STATE_CURRENT_PAGE, b.mainPager.getCurrentItem());
103         if (mainModel.getAccountFilter()
104                      .getValue() != null)
105             outState.putString(STATE_ACC_FILTER, mainModel.getAccountFilter()
106                                                           .getValue());
107     }
108     @Override
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;
118         super.onDestroy();
119     }
120     @Override
121     protected void onResume() {
122         super.onResume();
123         fabShouldShow();
124     }
125     @Override
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());
132
133         mainModel = new ViewModelProvider(this).get(MainModel.class);
134
135         mSectionsPagerAdapter = new SectionsPagerAdapter(this);
136
137         Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
138         if (extra != null && savedInstanceState == null)
139             savedInstanceState = extra;
140
141
142         setSupportActionBar(b.toolbar);
143
144         Data.observeProfile(this, this::onProfileChanged);
145
146         Data.profiles.observe(this, this::onProfileListChanged);
147         Data.backgroundTaskProgress.observe(this, this::onRetrieveProgress);
148         Data.backgroundTasksRunning.observe(this, this::onRetrieveRunningChanged);
149
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);
153         }
154         barDrawerToggle.syncState();
155
156         try {
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);
161         }
162         catch (Exception e) {
163             e.printStackTrace();
164         }
165
166         markDrawerItemCurrent(R.id.nav_account_summary);
167
168         b.mainPager.setAdapter(mSectionsPagerAdapter);
169
170         if (pageChangeCallback == null) {
171             pageChangeCallback = new ViewPager2.OnPageChangeCallback() {
172                 @Override
173                 public void onPageSelected(int position) {
174                     mCurrentPage = position;
175                     switch (position) {
176                         case 0:
177                             markDrawerItemCurrent(R.id.nav_account_summary);
178                             break;
179                         case 1:
180                             markDrawerItemCurrent(R.id.nav_latest_transactions);
181                             break;
182                         default:
183                             Log.e("MainActivity",
184                                     String.format("Unexpected page index %d", position));
185                     }
186
187                     super.onPageSelected(position);
188                 }
189             };
190             b.mainPager.registerOnPageChangeCallback(pageChangeCallback);
191         }
192
193         mCurrentPage = 0;
194         if (savedInstanceState != null) {
195             int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
196             if (currentPage != -1) {
197                 mCurrentPage = currentPage;
198             }
199             mainModel.getAccountFilter()
200                      .setValue(savedInstanceState.getString(STATE_ACC_FILTER, null));
201         }
202
203         b.btnNoProfilesAdd.setOnClickListener(v -> MobileLedgerProfile.startEditProfileActivity(this, null));
204
205         b.btnAddTransaction.setOnClickListener(this::fabNewTransactionClicked);
206
207         b.navNewProfileButton.setOnClickListener(v -> MobileLedgerProfile.startEditProfileActivity(this, null));
208
209         b.transactionListCancelDownload.setOnClickListener(this::onStopTransactionRefreshClick);
210
211         if (mProfileListAdapter == null)
212             mProfileListAdapter = new ProfilesRecyclerViewAdapter();
213         b.navProfileList.setAdapter(mProfileListAdapter);
214
215         mProfileListAdapter.editingProfiles.observe(this, newValue -> {
216             if (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));
227                 }
228             }
229             else {
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));
240                 }
241             }
242
243             mProfileListAdapter.notifyDataSetChanged();
244         });
245
246         LinearLayoutManager llm = new LinearLayoutManager(this);
247
248         llm.setOrientation(RecyclerView.VERTICAL);
249         b.navProfileList.setLayoutManager(llm);
250
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() {
256                 @Override
257                 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
258                     if (slideOffset > 0.2)
259                         fabHide();
260                 }
261                 @Override
262                 public void onDrawerClosed(View drawerView) {
263                     super.onDrawerClosed(drawerView);
264                     mProfileListAdapter.setAnimationsEnabled(false);
265                     mProfileListAdapter.editingProfiles.setValue(false);
266                     Data.drawerOpen.setValue(false);
267                     fabShouldShow();
268                 }
269                 @Override
270                 public void onDrawerOpened(View drawerView) {
271                     super.onDrawerOpened(drawerView);
272                     mProfileListAdapter.setAnimationsEnabled(true);
273                     Data.drawerOpen.setValue(true);
274                     fabHide();
275                 }
276             };
277             b.drawerLayout.addDrawerListener(drawerListener);
278         }
279
280         Data.drawerOpen.observe(this, open -> {
281             if (open)
282                 b.drawerLayout.open();
283             else
284                 b.drawerLayout.close();
285         });
286
287         mainModel.getUpdateError()
288                  .observe(this, (error) -> {
289                      if (error == null)
290                          return;
291
292                      Snackbar.make(b.mainPager, error, Snackbar.LENGTH_INDEFINITE)
293                              .show();
294                      mainModel.clearUpdateError();
295                  });
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);
303     }
304     private void onPatternsClick(View view) {
305         Intent intent = new Intent(this, TemplatesActivity.class);
306         startActivity(intent);
307     }
308     private void scheduleDataRetrievalIfStale(long lastUpdate) {
309         long now = new Date().getTime();
310         if ((lastUpdate == 0) || (now > (lastUpdate + (24 * 3600 * 1000)))) {
311             if (lastUpdate == 0)
312                 Logger.debug("db::", "WEB data never fetched. scheduling a fetch");
313             else
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));
317
318             mainModel.scheduleTransactionListRetrieval();
319         }
320     }
321     private void createShortcuts(List<MobileLedgerProfile> list) {
322         if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
323             return;
324
325         ShortcutManager sm = getSystemService(ShortcutManager.class);
326         List<ShortcutInfo> shortcuts = new ArrayList<>();
327         int i = 0;
328         for (MobileLedgerProfile p : list) {
329             if (shortcuts.size() >= sm.getMaxShortcutCountPerActivity())
330                 break;
331
332             if (!p.isPostingPermitted())
333                 continue;
334
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",
342                                              p.getUuid()))
343                                      .setRank(i)
344                                      .build();
345             shortcuts.add(si);
346             i++;
347         }
348         sm.setDynamicShortcuts(shortcuts);
349     }
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);
354             return;
355         }
356
357         b.mainAppLayout.setVisibility(View.VISIBLE);
358         b.noProfilesLayout.setVisibility(View.GONE);
359
360         b.navProfileList.setMinimumHeight(
361                 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
362
363         Logger.debug("profiles", "profile list changed");
364         mProfileListAdapter.notifyDataSetChanged();
365
366         createShortcuts(newList);
367     }
368     /**
369      * called when the current profile has changed
370      */
371     private void onProfileChanged(MobileLedgerProfile profile) {
372         if (this.profile == null) {
373             if (profile == null)
374                 return;
375         }
376         else {
377             if (this.profile.equals(profile))
378                 return;
379         }
380
381         boolean haveProfile = profile != null;
382
383         if (haveProfile)
384             setTitle(profile.getName());
385         else
386             setTitle(R.string.app_name);
387
388         mainModel.setProfile(profile);
389
390         this.profile = profile;
391
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,
396                             newProfileTheme));
397             Colors.profileThemeId = newProfileTheme;
398             profileThemeChanged();
399             // profileThemeChanged would restart the activity, so no need to reload the
400             // data sets below
401             return;
402         }
403
404         b.noProfilesLayout.setVisibility(haveProfile ? View.GONE : View.VISIBLE);
405         b.pagerLayout.setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
406
407         mProfileListAdapter.notifyDataSetChanged();
408
409         mainModel.clearAccounts();
410         mainModel.clearTransactions();
411
412         if (haveProfile) {
413             mainModel.scheduleAccountListReload();
414             Logger.debug("transactions", "requesting list reload");
415             mainModel.scheduleTransactionListReload();
416
417             if (profile.isPostingPermitted()) {
418                 b.toolbar.setSubtitle(null);
419                 b.btnAddTransaction.show();
420             }
421             else {
422                 b.toolbar.setSubtitle(R.string.profile_subtitle_read_only);
423                 b.btnAddTransaction.hide();
424             }
425         }
426         else {
427             b.toolbar.setSubtitle(null);
428             b.btnAddTransaction.hide();
429         }
430
431         updateLastUpdateTextFromDB();
432     }
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);
440
441         recreate();
442     }
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);
447     }
448     public void markDrawerItemCurrent(int id) {
449         TextView item = b.drawerLayout.findViewById(id);
450         item.setBackgroundColor(Colors.tableRowDarkBG);
451
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);
456             }
457         }
458     }
459     public void onAccountSummaryClicked(View view) {
460         b.drawerLayout.closeDrawers();
461
462         showAccountSummaryFragment();
463     }
464     private void showAccountSummaryFragment() {
465         b.mainPager.setCurrentItem(0, true);
466         mainModel.getAccountFilter()
467                  .setValue(null);
468     }
469     public void onLatestTransactionsClicked(View view) {
470         b.drawerLayout.closeDrawers();
471
472         showTransactionsFragment(null);
473     }
474     public void showTransactionsFragment(String accName) {
475         mainModel.getAccountFilter()
476                  .setValue(accName);
477         b.mainPager.setCurrentItem(1, true);
478     }
479     public void showAccountTransactions(String accountName) {
480         mBackMeansToAccountList = true;
481         showTransactionsFragment(accountName);
482     }
483     @Override
484     public void onBackPressed() {
485         if (b.drawerLayout.isDrawerOpen(GravityCompat.START)) {
486             b.drawerLayout.closeDrawer(GravityCompat.START);
487         }
488         else {
489             if (mBackMeansToAccountList && (b.mainPager.getCurrentItem() == 1)) {
490                 mainModel.getAccountFilter()
491                          .setValue(null);
492                 showAccountSummaryFragment();
493                 mBackMeansToAccountList = false;
494             }
495             else {
496                 Logger.debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
497                         getSupportFragmentManager().getBackStackEntryCount()));
498
499                 super.onBackPressed();
500             }
501         }
502     }
503     public void updateLastUpdateTextFromDB() {
504         if (profile == null)
505             return;
506
507         long lastUpdate = profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
508
509         Logger.debug("transactions", String.format(Locale.ENGLISH, "Last update = %d", lastUpdate));
510         if (lastUpdate == 0) {
511             Data.lastUpdateDate.postValue(null);
512         }
513         else {
514             Data.lastUpdateDate.postValue(new Date(lastUpdate));
515         }
516
517         scheduleDataRetrievalIfStale(lastUpdate);
518
519     }
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("----");
532         }
533         else {
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)));
543         }
544     }
545     public void onStopTransactionRefreshClick(View view) {
546         Logger.debug("interactive", "Cancelling transactions refresh");
547         mainModel.stopTransactionsRetrieval();
548         b.transactionListCancelDownload.setEnabled(false);
549     }
550     public void onRetrieveRunningChanged(Boolean running) {
551         if (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);
559             }
560             else {
561                 b.transactionListProgressBar.setProgress(0);
562             }
563             b.transactionProgressLayout.setVisibility(View.VISIBLE);
564         }
565         else {
566             b.transactionProgressLayout.setVisibility(View.GONE);
567         }
568     }
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);
573
574             mainModel.transactionRetrievalDone();
575
576             String error = progress.getError();
577             if (error != null) {
578                 if (error.equals(RetrieveTransactionsTask.Result.ERR_JSON_PARSER_ERROR))
579                     error = getResources().getString(R.string.err_json_parser_error);
580
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);
586                 });
587                 builder.create()
588                        .show();
589                 return;
590             }
591
592             return;
593         }
594
595
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);
602 //        else
603 //            progressBar.setProgress(0);
604         b.transactionProgressLayout.setVisibility(View.VISIBLE);
605
606         if (progress.isIndeterminate() || (progress.getTotal() <= 0)) {
607             b.transactionListProgressBar.setIndeterminate(true);
608             Logger.debug("progress", "indeterminate");
609         }
610         else {
611             if (b.transactionListProgressBar.isIndeterminate()) {
612                 b.transactionListProgressBar.setIndeterminate(false);
613             }
614 //            Logger.debug("progress",
615 //                    String.format(Locale.US, "%d/%d", progress.getProgress(), progress.getTotal
616 //                    ()));
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);
622             else
623                 b.transactionListProgressBar.setProgress(progress.getProgress());
624         }
625     }
626     public void fabShouldShow() {
627         if ((profile != null) && profile.isPostingPermitted() && !b.drawerLayout.isOpen())
628             b.btnAddTransaction.show();
629         else
630             fabHide();
631     }
632     public void fabHide() {
633         b.btnAddTransaction.hide();
634     }
635
636     public static class SectionsPagerAdapter extends FragmentStateAdapter {
637
638         public SectionsPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
639             super(fragmentActivity);
640         }
641         @NotNull
642         @Override
643         public Fragment createFragment(int position) {
644             Logger.debug("main",
645                     String.format(Locale.ENGLISH, "Switching to fragment %d", position));
646             switch (position) {
647                 case 0:
648 //                    debug("flow", "Creating account summary fragment");
649                     return new AccountSummaryFragment();
650                 case 1:
651                     return new TransactionListFragment();
652                 default:
653                     throw new IllegalStateException(
654                             String.format("Unexpected fragment index: " + "%d", position));
655             }
656         }
657
658         @Override
659         public int getItemCount() {
660             return 2;
661         }
662     }
663 }