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