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