]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
Room-based profile management
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / MainActivity.java
1 /*
2  * Copyright © 2021 Damyan Ivanov.
3  * This file is part of MoLe.
4  * MoLe is free software: you can distribute it and/or modify it
5  * under the term of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your opinion), any later version.
8  *
9  * MoLe is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License terms for details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.ui.activity;
19
20 import android.content.Context;
21 import android.content.Intent;
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.text.format.DateUtils;
31 import android.util.Log;
32 import android.view.View;
33 import android.view.animation.AnimationUtils;
34 import android.widget.TextView;
35
36 import androidx.annotation.NonNull;
37 import androidx.annotation.Nullable;
38 import androidx.appcompat.app.ActionBarDrawerToggle;
39 import androidx.appcompat.app.AlertDialog;
40 import androidx.core.view.GravityCompat;
41 import androidx.drawerlayout.widget.DrawerLayout;
42 import androidx.fragment.app.Fragment;
43 import androidx.fragment.app.FragmentActivity;
44 import androidx.lifecycle.ViewModelProvider;
45 import androidx.recyclerview.widget.LinearLayoutManager;
46 import androidx.recyclerview.widget.RecyclerView;
47 import androidx.viewpager2.adapter.FragmentStateAdapter;
48 import androidx.viewpager2.widget.ViewPager2;
49
50 import com.google.android.material.snackbar.Snackbar;
51
52 import net.ktnx.mobileledger.R;
53 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
54 import net.ktnx.mobileledger.databinding.ActivityMainBinding;
55 import net.ktnx.mobileledger.db.DB;
56 import net.ktnx.mobileledger.db.Profile;
57 import net.ktnx.mobileledger.model.Data;
58 import net.ktnx.mobileledger.ui.FabManager;
59 import net.ktnx.mobileledger.ui.MainModel;
60 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
61 import net.ktnx.mobileledger.ui.new_transaction.NewTransactionActivity;
62 import net.ktnx.mobileledger.ui.profiles.ProfileDetailActivity;
63 import net.ktnx.mobileledger.ui.profiles.ProfilesRecyclerViewAdapter;
64 import net.ktnx.mobileledger.ui.templates.TemplatesActivity;
65 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
66 import net.ktnx.mobileledger.utils.Colors;
67 import net.ktnx.mobileledger.utils.Logger;
68 import net.ktnx.mobileledger.utils.MLDB;
69
70 import org.jetbrains.annotations.NotNull;
71
72 import java.util.ArrayList;
73 import java.util.Date;
74 import java.util.List;
75 import java.util.Locale;
76 import java.util.Objects;
77
78 /*
79  * TODO: reports
80  *  */
81
82 public class MainActivity extends ProfileThemedActivity implements FabManager.FabHandler {
83     public static final String STATE_CURRENT_PAGE = "current_page";
84     public static final String BUNDLE_SAVED_STATE = "bundle_savedState";
85     public static final String STATE_ACC_FILTER = "account_filter";
86     private static final boolean FAB_HIDDEN = false;
87     private static final boolean FAB_SHOWN = true;
88     private SectionsPagerAdapter mSectionsPagerAdapter;
89     private ProfilesRecyclerViewAdapter mProfileListAdapter;
90     private int mCurrentPage;
91     private boolean mBackMeansToAccountList = false;
92     private DrawerLayout.SimpleDrawerListener drawerListener;
93     private ActionBarDrawerToggle barDrawerToggle;
94     private ViewPager2.OnPageChangeCallback pageChangeCallback;
95     private Profile profile;
96     private MainModel mainModel;
97     private ActivityMainBinding b;
98     private int fabVerticalOffset;
99     private FabManager fabManager;
100     @Override
101     protected void onStart() {
102         super.onStart();
103
104         Logger.debug("MainActivity", "onStart()");
105
106         b.mainPager.setCurrentItem(mCurrentPage, false);
107     }
108     @Override
109     protected void onSaveInstanceState(@NotNull Bundle outState) {
110         super.onSaveInstanceState(outState);
111         outState.putInt(STATE_CURRENT_PAGE, b.mainPager.getCurrentItem());
112         if (mainModel.getAccountFilter()
113                      .getValue() != null)
114             outState.putString(STATE_ACC_FILTER, mainModel.getAccountFilter()
115                                                           .getValue());
116     }
117     @Override
118     protected void onDestroy() {
119         mSectionsPagerAdapter = null;
120         b.navProfileList.setAdapter(null);
121         b.drawerLayout.removeDrawerListener(drawerListener);
122         drawerListener = null;
123         b.drawerLayout.removeDrawerListener(barDrawerToggle);
124         barDrawerToggle = null;
125         b.mainPager.unregisterOnPageChangeCallback(pageChangeCallback);
126         pageChangeCallback = null;
127         super.onDestroy();
128     }
129     @Override
130     protected void onResume() {
131         super.onResume();
132         fabShouldShow();
133     }
134     @Override
135     protected void onCreate(Bundle savedInstanceState) {
136         Logger.debug("MainActivity", "onCreate()/entry");
137         super.onCreate(savedInstanceState);
138         Logger.debug("MainActivity", "onCreate()/after super");
139         b = ActivityMainBinding.inflate(getLayoutInflater());
140         setContentView(b.getRoot());
141
142         mainModel = new ViewModelProvider(this).get(MainModel.class);
143
144         mSectionsPagerAdapter = new SectionsPagerAdapter(this);
145
146         Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
147         if (extra != null && savedInstanceState == null)
148             savedInstanceState = extra;
149
150
151         setSupportActionBar(b.toolbar);
152
153         Data.observeProfile(this, this::onProfileChanged);
154
155         Data.profiles.observe(this, this::onProfileListChanged);
156
157         Data.backgroundTaskProgress.observe(this, this::onRetrieveProgress);
158         Data.backgroundTasksRunning.observe(this, this::onRetrieveRunningChanged);
159
160         if (barDrawerToggle == null) {
161             barDrawerToggle = new ActionBarDrawerToggle(this, b.drawerLayout, b.toolbar,
162                     R.string.navigation_drawer_open, R.string.navigation_drawer_close);
163             b.drawerLayout.addDrawerListener(barDrawerToggle);
164         }
165         barDrawerToggle.syncState();
166
167         try {
168             PackageInfo pi = getApplicationContext().getPackageManager()
169                                                     .getPackageInfo(getPackageName(), 0);
170             ((TextView) b.navUpper.findViewById(R.id.drawer_version_text)).setText(pi.versionName);
171             ((TextView) b.noProfilesLayout.findViewById(R.id.drawer_version_text)).setText(
172                     pi.versionName);
173         }
174         catch (Exception e) {
175             e.printStackTrace();
176         }
177
178         markDrawerItemCurrent(R.id.nav_account_summary);
179
180         b.mainPager.setAdapter(mSectionsPagerAdapter);
181
182         if (pageChangeCallback == null) {
183             pageChangeCallback = new ViewPager2.OnPageChangeCallback() {
184                 @Override
185                 public void onPageSelected(int position) {
186                     mCurrentPage = position;
187                     switch (position) {
188                         case 0:
189                             markDrawerItemCurrent(R.id.nav_account_summary);
190                             break;
191                         case 1:
192                             markDrawerItemCurrent(R.id.nav_latest_transactions);
193                             break;
194                         default:
195                             Log.e("MainActivity",
196                                     String.format("Unexpected page index %d", position));
197                     }
198
199                     super.onPageSelected(position);
200                 }
201             };
202             b.mainPager.registerOnPageChangeCallback(pageChangeCallback);
203         }
204
205         mCurrentPage = 0;
206         if (savedInstanceState != null) {
207             int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
208             if (currentPage != -1) {
209                 mCurrentPage = currentPage;
210             }
211             mainModel.getAccountFilter()
212                      .setValue(savedInstanceState.getString(STATE_ACC_FILTER, null));
213         }
214
215         b.btnNoProfilesAdd.setOnClickListener(v -> ProfileDetailActivity.start(this, null));
216
217         b.btnAddTransaction.setOnClickListener(this::fabNewTransactionClicked);
218
219         b.navNewProfileButton.setOnClickListener(v -> ProfileDetailActivity.start(this, null));
220
221         b.transactionListCancelDownload.setOnClickListener(this::onStopTransactionRefreshClick);
222
223         if (mProfileListAdapter == null)
224             mProfileListAdapter = new ProfilesRecyclerViewAdapter();
225         b.navProfileList.setAdapter(mProfileListAdapter);
226
227         mProfileListAdapter.editingProfiles.observe(this, newValue -> {
228             if (newValue) {
229                 b.navProfilesStartEdit.setVisibility(View.GONE);
230                 b.navProfilesCancelEdit.setVisibility(View.VISIBLE);
231                 b.navNewProfileButton.setVisibility(View.VISIBLE);
232                 if (b.drawerLayout.isDrawerOpen(GravityCompat.START)) {
233                     b.navProfilesStartEdit.startAnimation(
234                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
235                     b.navProfilesCancelEdit.startAnimation(
236                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
237                     b.navNewProfileButton.startAnimation(
238                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
239                 }
240             }
241             else {
242                 b.navProfilesCancelEdit.setVisibility(View.GONE);
243                 b.navProfilesStartEdit.setVisibility(View.VISIBLE);
244                 b.navNewProfileButton.setVisibility(View.GONE);
245                 if (b.drawerLayout.isDrawerOpen(GravityCompat.START)) {
246                     b.navProfilesCancelEdit.startAnimation(
247                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
248                     b.navProfilesStartEdit.startAnimation(
249                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
250                     b.navNewProfileButton.startAnimation(
251                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
252                 }
253             }
254
255             mProfileListAdapter.notifyDataSetChanged();
256         });
257
258         fabManager = new FabManager(b.btnAddTransaction);
259
260         LinearLayoutManager llm = new LinearLayoutManager(this);
261
262         llm.setOrientation(RecyclerView.VERTICAL);
263         b.navProfileList.setLayoutManager(llm);
264
265         b.navProfilesStartEdit.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
266         b.navProfilesCancelEdit.setOnClickListener(
267                 (v) -> mProfileListAdapter.flipEditingProfiles());
268         b.navProfileListHeadButtons.setOnClickListener(
269                 (v) -> mProfileListAdapter.flipEditingProfiles());
270         if (drawerListener == null) {
271             drawerListener = new DrawerLayout.SimpleDrawerListener() {
272                 @Override
273                 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
274                     if (slideOffset > 0.2)
275                         fabManager.hideFab();
276                 }
277                 @Override
278                 public void onDrawerClosed(View drawerView) {
279                     super.onDrawerClosed(drawerView);
280                     mProfileListAdapter.setAnimationsEnabled(false);
281                     mProfileListAdapter.editingProfiles.setValue(false);
282                     Data.drawerOpen.setValue(false);
283                     fabShouldShow();
284                 }
285                 @Override
286                 public void onDrawerOpened(View drawerView) {
287                     super.onDrawerOpened(drawerView);
288                     mProfileListAdapter.setAnimationsEnabled(true);
289                     Data.drawerOpen.setValue(true);
290                     fabManager.hideFab();
291                 }
292             };
293             b.drawerLayout.addDrawerListener(drawerListener);
294         }
295
296         Data.drawerOpen.observe(this, open -> {
297             if (open)
298                 b.drawerLayout.open();
299             else
300                 b.drawerLayout.close();
301         });
302
303         mainModel.getUpdateError()
304                  .observe(this, (error) -> {
305                      if (error == null)
306                          return;
307
308                      Snackbar.make(b.mainPager, error, Snackbar.LENGTH_INDEFINITE)
309                              .show();
310                      mainModel.clearUpdateError();
311                  });
312         Data.locale.observe(this, l -> refreshLastUpdateInfo());
313         Data.lastUpdateDate.observe(this, date -> refreshLastUpdateInfo());
314         Data.lastUpdateTransactionCount.observe(this, date -> refreshLastUpdateInfo());
315         Data.lastUpdateAccountCount.observe(this, date -> refreshLastUpdateInfo());
316         b.navAccountSummary.setOnClickListener(this::onAccountSummaryClicked);
317         b.navLatestTransactions.setOnClickListener(this::onLatestTransactionsClicked);
318         b.navPatterns.setOnClickListener(this::onPatternsClick);
319     }
320     private void onPatternsClick(View view) {
321         Intent intent = new Intent(this, TemplatesActivity.class);
322         startActivity(intent);
323     }
324     private void scheduleDataRetrievalIfStale(long lastUpdate) {
325         long now = new Date().getTime();
326         if ((lastUpdate == 0) || (now > (lastUpdate + (24 * 3600 * 1000)))) {
327             if (lastUpdate == 0)
328                 Logger.debug("db::", "WEB data never fetched. scheduling a fetch");
329             else
330                 Logger.debug("db", String.format(Locale.ENGLISH,
331                         "WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
332                         lastUpdate / 1000f, now / 1000f));
333
334             mainModel.scheduleTransactionListRetrieval();
335         }
336     }
337     private void createShortcuts(List<Profile> list) {
338         if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
339             return;
340
341         ShortcutManager sm = getSystemService(ShortcutManager.class);
342         List<ShortcutInfo> shortcuts = new ArrayList<>();
343         int i = 0;
344         for (Profile p : list) {
345             if (shortcuts.size() >= sm.getMaxShortcutCountPerActivity())
346                 break;
347
348             if (!p.permitPosting())
349                 continue;
350
351             final ShortcutInfo.Builder builder =
352                     new ShortcutInfo.Builder(this, "new_transaction_" + p.getId());
353             ShortcutInfo si = builder.setShortLabel(p.getName())
354                                      .setIcon(Icon.createWithResource(this,
355                                              R.drawable.thick_plus_icon))
356                                      .setIntent(new Intent(Intent.ACTION_VIEW, null, this,
357                                              NewTransactionActivity.class).putExtra(
358                                              ProfileThemedActivity.PARAM_PROFILE_ID, p.getId())
359                                                                           .putExtra(
360                                                                                   ProfileThemedActivity.PARAM_THEME,
361                                                                                   p.getTheme()))
362                                      .setRank(i)
363                                      .build();
364             shortcuts.add(si);
365             i++;
366         }
367         sm.setDynamicShortcuts(shortcuts);
368     }
369     private void onProfileListChanged(List<Profile> newList) {
370         if ((newList == null) || newList.isEmpty()) {
371             b.noProfilesLayout.setVisibility(View.VISIBLE);
372             b.mainAppLayout.setVisibility(View.GONE);
373             return;
374         }
375
376         b.mainAppLayout.setVisibility(View.VISIBLE);
377         b.noProfilesLayout.setVisibility(View.GONE);
378
379         b.navProfileList.setMinimumHeight(
380                 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
381
382         Logger.debug("profiles", "profile list changed");
383         mProfileListAdapter.setProfileList(newList);
384
385         createShortcuts(newList);
386     }
387     /**
388      * called when the current profile has changed
389      */
390     private void onProfileChanged(@Nullable Profile newProfile) {
391         if (this.profile == null) {
392             if (newProfile == null)
393                 return;
394         }
395         else {
396             if (this.profile.equals(newProfile))
397                 return;
398         }
399
400         boolean haveProfile = newProfile != null;
401
402         if (haveProfile)
403             setTitle(newProfile.getName());
404         else
405             setTitle(R.string.app_name);
406
407         int newProfileTheme = haveProfile ? newProfile.getTheme() : -1;
408         if (newProfileTheme != Colors.profileThemeId) {
409             Logger.debug("profiles",
410                     String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
411                             newProfileTheme));
412             Colors.profileThemeId = newProfileTheme;
413             profileThemeChanged();
414             // profileThemeChanged would restart the activity, so no need to reload the
415             // data sets below
416             return;
417         }
418
419         final boolean sameProfileId = (newProfile != null) && (this.profile != null) &&
420                                       this.profile.getId() == newProfile.getId();
421
422         this.profile = newProfile;
423
424         b.noProfilesLayout.setVisibility(haveProfile ? View.GONE : View.VISIBLE);
425         b.pagerLayout.setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
426
427         mProfileListAdapter.notifyDataSetChanged();
428
429         if (haveProfile) {
430             if (newProfile.permitPosting()) {
431                 b.toolbar.setSubtitle(null);
432                 b.btnAddTransaction.show();
433             }
434             else {
435                 b.toolbar.setSubtitle(R.string.profile_subtitle_read_only);
436                 b.btnAddTransaction.hide();
437             }
438         }
439         else {
440             b.toolbar.setSubtitle(null);
441             b.btnAddTransaction.hide();
442         }
443
444         updateLastUpdateTextFromDB();
445
446         if (sameProfileId) {
447             Logger.debug(TAG, String.format(Locale.ROOT, "Short-cut profile 'changed' to %d",
448                     newProfile.getId()));
449             return;
450         }
451
452         mainModel.stopTransactionsRetrieval();
453
454         mainModel.clearTransactions();
455
456         if (haveProfile) {
457             Logger.debug("transactions", "requesting list reload");
458             mainModel.scheduleTransactionListReload();
459         }
460     }
461     private void profileThemeChanged() {
462         // un-hook all observed LiveData
463         Data.removeProfileObservers(this);
464         Data.profiles.removeObservers(this);
465         Data.lastUpdateTransactionCount.removeObservers(this);
466         Data.lastUpdateAccountCount.removeObservers(this);
467         Data.lastUpdateDate.removeObservers(this);
468
469         Logger.debug("MainActivity", "profileThemeChanged(): recreating activity");
470         recreate();
471     }
472     public void fabNewTransactionClicked(View view) {
473         Intent intent = new Intent(this, NewTransactionActivity.class);
474         intent.putExtra(ProfileThemedActivity.PARAM_PROFILE_ID, profile.getId());
475         intent.putExtra(ProfileThemedActivity.PARAM_THEME, profile.getTheme());
476         startActivity(intent);
477         overridePendingTransition(R.anim.slide_in_up, R.anim.dummy);
478     }
479     public void markDrawerItemCurrent(int id) {
480         TextView item = b.drawerLayout.findViewById(id);
481         item.setBackgroundColor(Colors.tableRowDarkBG);
482
483         for (int i = 0; i < b.navActions.getChildCount(); i++) {
484             View view = b.navActions.getChildAt(i);
485             if (view.getId() != id) {
486                 view.setBackgroundColor(Color.TRANSPARENT);
487             }
488         }
489     }
490     public void onAccountSummaryClicked(View view) {
491         b.drawerLayout.closeDrawers();
492
493         showAccountSummaryFragment();
494     }
495     private void showAccountSummaryFragment() {
496         b.mainPager.setCurrentItem(0, true);
497         mainModel.getAccountFilter()
498                  .setValue(null);
499     }
500     public void onLatestTransactionsClicked(View view) {
501         b.drawerLayout.closeDrawers();
502
503         showTransactionsFragment(null);
504     }
505     public void showTransactionsFragment(String accName) {
506         mainModel.getAccountFilter()
507                  .setValue(accName);
508         b.mainPager.setCurrentItem(1, true);
509     }
510     public void showAccountTransactions(String accountName) {
511         mBackMeansToAccountList = true;
512         showTransactionsFragment(accountName);
513     }
514     @Override
515     public void onBackPressed() {
516         if (b.drawerLayout.isDrawerOpen(GravityCompat.START)) {
517             b.drawerLayout.closeDrawer(GravityCompat.START);
518         }
519         else {
520             if (mBackMeansToAccountList && (b.mainPager.getCurrentItem() == 1)) {
521                 mainModel.getAccountFilter()
522                          .setValue(null);
523                 showAccountSummaryFragment();
524                 mBackMeansToAccountList = false;
525             }
526             else {
527                 Logger.debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
528                         getSupportFragmentManager().getBackStackEntryCount()));
529
530                 super.onBackPressed();
531             }
532         }
533     }
534     public void updateLastUpdateTextFromDB() {
535         if (profile == null)
536             return;
537
538         DB.get()
539           .getOptionDAO()
540           .load(profile.getId(), MLDB.OPT_LAST_SCRAPE)
541           .observe(this, opt -> {
542               long lastUpdate = 0;
543               if (opt != null) {
544                   try {
545                       lastUpdate = Long.parseLong(opt.getValue());
546                   }
547                   catch (NumberFormatException ex) {
548                       Logger.debug(TAG, String.format("Error parsing '%s' as long", opt.getValue()),
549                               ex);
550                   }
551               }
552
553               if (lastUpdate == 0) {
554                   Data.lastUpdateDate.postValue(null);
555               }
556               else {
557                   Data.lastUpdateDate.postValue(new Date(lastUpdate));
558               }
559
560               scheduleDataRetrievalIfStale(lastUpdate);
561           });
562     }
563     private void refreshLastUpdateInfo() {
564         final int formatFlags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR |
565                                 DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_NUMERIC_DATE;
566         String templateForTransactions =
567                 getResources().getString(R.string.transaction_count_summary);
568         String templateForAccounts = getResources().getString(R.string.account_count_summary);
569         Integer accountCount = Data.lastUpdateAccountCount.getValue();
570         Integer transactionCount = Data.lastUpdateTransactionCount.getValue();
571         Date lastUpdate = Data.lastUpdateDate.getValue();
572         if (lastUpdate == null) {
573             Data.lastTransactionsUpdateText.setValue("----");
574             Data.lastAccountsUpdateText.setValue("----");
575         }
576         else {
577             Data.lastTransactionsUpdateText.setValue(
578                     String.format(Objects.requireNonNull(Data.locale.getValue()),
579                             templateForTransactions,
580                             transactionCount == null ? 0 : transactionCount,
581                             DateUtils.formatDateTime(this, lastUpdate.getTime(), formatFlags)));
582             Data.lastAccountsUpdateText.setValue(
583                     String.format(Objects.requireNonNull(Data.locale.getValue()),
584                             templateForAccounts, accountCount == null ? 0 : accountCount,
585                             DateUtils.formatDateTime(this, lastUpdate.getTime(), formatFlags)));
586         }
587     }
588     public void onStopTransactionRefreshClick(View view) {
589         Logger.debug("interactive", "Cancelling transactions refresh");
590         mainModel.stopTransactionsRetrieval();
591         b.transactionListCancelDownload.setEnabled(false);
592     }
593     public void onRetrieveRunningChanged(Boolean running) {
594         if (running) {
595             b.transactionListCancelDownload.setEnabled(true);
596             ColorStateList csl = Colors.getColorStateList();
597             b.transactionListProgressBar.setIndeterminateTintList(csl);
598             b.transactionListProgressBar.setProgressTintList(csl);
599             b.transactionListProgressBar.setIndeterminate(true);
600             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
601                 b.transactionListProgressBar.setProgress(0, false);
602             }
603             else {
604                 b.transactionListProgressBar.setProgress(0);
605             }
606             b.transactionProgressLayout.setVisibility(View.VISIBLE);
607         }
608         else {
609             b.transactionProgressLayout.setVisibility(View.GONE);
610         }
611     }
612     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
613         if (progress.getState() == RetrieveTransactionsTask.ProgressState.FINISHED) {
614             Logger.debug("progress", "Done");
615             b.transactionProgressLayout.setVisibility(View.GONE);
616
617             mainModel.transactionRetrievalDone();
618
619             String error = progress.getError();
620             if (error != null) {
621                 if (error.equals(RetrieveTransactionsTask.Result.ERR_JSON_PARSER_ERROR))
622                     error = getResources().getString(R.string.err_json_parser_error);
623
624                 AlertDialog.Builder builder = new AlertDialog.Builder(this);
625                 builder.setMessage(error);
626                 builder.setPositiveButton(R.string.btn_profile_options, (dialog, which) -> {
627                     Logger.debug("error", "will start profile editor");
628                     ProfileDetailActivity.start(this, profile);
629                 });
630                 builder.create()
631                        .show();
632                 return;
633             }
634
635             return;
636         }
637
638
639         b.transactionListCancelDownload.setEnabled(true);
640 //        ColorStateList csl = Colors.getColorStateList();
641 //        progressBar.setIndeterminateTintList(csl);
642 //        progressBar.setProgressTintList(csl);
643 //        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
644 //            progressBar.setProgress(0, false);
645 //        else
646 //            progressBar.setProgress(0);
647         b.transactionProgressLayout.setVisibility(View.VISIBLE);
648
649         if (progress.isIndeterminate() || (progress.getTotal() <= 0)) {
650             b.transactionListProgressBar.setIndeterminate(true);
651             Logger.debug("progress", "indeterminate");
652         }
653         else {
654             if (b.transactionListProgressBar.isIndeterminate()) {
655                 b.transactionListProgressBar.setIndeterminate(false);
656             }
657 //            Logger.debug("progress",
658 //                    String.format(Locale.US, "%d/%d", progress.getProgress(), progress.getTotal
659 //                    ()));
660             b.transactionListProgressBar.setMax(progress.getTotal());
661             // for some reason animation doesn't work - no progress is shown (stick at 0)
662             // on lineageOS 14.1 (Nougat, 7.1.2)
663             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
664                 b.transactionListProgressBar.setProgress(progress.getProgress(), false);
665             else
666                 b.transactionListProgressBar.setProgress(progress.getProgress());
667         }
668     }
669     public void fabShouldShow() {
670         if ((profile != null) && profile.permitPosting() && !b.drawerLayout.isOpen())
671             fabManager.showFab();
672     }
673     @Override
674     public Context getContext() {
675         return this;
676     }
677     @Override
678     public void showManagedFab() {
679         fabShouldShow();
680     }
681     @Override
682     public void hideManagedFab() {
683         fabManager.hideFab();
684     }
685     public static class SectionsPagerAdapter extends FragmentStateAdapter {
686
687         public SectionsPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
688             super(fragmentActivity);
689         }
690         @NotNull
691         @Override
692         public Fragment createFragment(int position) {
693             Logger.debug("main",
694                     String.format(Locale.ENGLISH, "Switching to fragment %d", position));
695             switch (position) {
696                 case 0:
697 //                    debug("flow", "Creating account summary fragment");
698                     return new AccountSummaryFragment();
699                 case 1:
700                     return new TransactionListFragment();
701                 default:
702                     throw new IllegalStateException(
703                             String.format("Unexpected fragment index: " + "%d", position));
704             }
705         }
706
707         @Override
708         public int getItemCount() {
709             return 2;
710         }
711     }
712 }