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