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