]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
when deleting the currently active profile, switch to the first profile
[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         Profile currentProfile = Data.getProfile();
388         if (currentProfile == null || !newList.contains(currentProfile)) {
389             Logger.debug(TAG, "Switching profile because the current is no longer available");
390             Data.setCurrentProfile(newList.get(0));
391         }
392     }
393     /**
394      * called when the current profile has changed
395      */
396     private void onProfileChanged(@Nullable Profile newProfile) {
397         if (this.profile == null) {
398             if (newProfile == null)
399                 return;
400         }
401         else {
402             if (this.profile.equals(newProfile))
403                 return;
404         }
405
406         boolean haveProfile = newProfile != null;
407
408         if (haveProfile)
409             setTitle(newProfile.getName());
410         else
411             setTitle(R.string.app_name);
412
413         int newProfileTheme = haveProfile ? newProfile.getTheme() : -1;
414         if (newProfileTheme != Colors.profileThemeId) {
415             Logger.debug("profiles",
416                     String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
417                             newProfileTheme));
418             Colors.profileThemeId = newProfileTheme;
419             profileThemeChanged();
420             // profileThemeChanged would restart the activity, so no need to reload the
421             // data sets below
422             return;
423         }
424
425         final boolean sameProfileId = (newProfile != null) && (this.profile != null) &&
426                                       this.profile.getId() == newProfile.getId();
427
428         this.profile = newProfile;
429
430         b.noProfilesLayout.setVisibility(haveProfile ? View.GONE : View.VISIBLE);
431         b.pagerLayout.setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
432
433         mProfileListAdapter.notifyDataSetChanged();
434
435         if (haveProfile) {
436             if (newProfile.permitPosting()) {
437                 b.toolbar.setSubtitle(null);
438                 b.btnAddTransaction.show();
439             }
440             else {
441                 b.toolbar.setSubtitle(R.string.profile_subtitle_read_only);
442                 b.btnAddTransaction.hide();
443             }
444         }
445         else {
446             b.toolbar.setSubtitle(null);
447             b.btnAddTransaction.hide();
448         }
449
450         updateLastUpdateTextFromDB();
451
452         if (sameProfileId) {
453             Logger.debug(TAG, String.format(Locale.ROOT, "Short-cut profile 'changed' to %d",
454                     newProfile.getId()));
455             return;
456         }
457
458         mainModel.stopTransactionsRetrieval();
459
460         mainModel.clearTransactions();
461
462         if (haveProfile) {
463             Logger.debug("transactions", "requesting list reload");
464             mainModel.scheduleTransactionListReload();
465         }
466     }
467     private void profileThemeChanged() {
468         // un-hook all observed LiveData
469         Data.removeProfileObservers(this);
470         Data.profiles.removeObservers(this);
471         Data.lastUpdateTransactionCount.removeObservers(this);
472         Data.lastUpdateAccountCount.removeObservers(this);
473         Data.lastUpdateDate.removeObservers(this);
474
475         Logger.debug("MainActivity", "profileThemeChanged(): recreating activity");
476         recreate();
477     }
478     public void fabNewTransactionClicked(View view) {
479         Intent intent = new Intent(this, NewTransactionActivity.class);
480         intent.putExtra(ProfileThemedActivity.PARAM_PROFILE_ID, profile.getId());
481         intent.putExtra(ProfileThemedActivity.PARAM_THEME, profile.getTheme());
482         startActivity(intent);
483         overridePendingTransition(R.anim.slide_in_up, R.anim.dummy);
484     }
485     public void markDrawerItemCurrent(int id) {
486         TextView item = b.drawerLayout.findViewById(id);
487         item.setBackgroundColor(Colors.tableRowDarkBG);
488
489         for (int i = 0; i < b.navActions.getChildCount(); i++) {
490             View view = b.navActions.getChildAt(i);
491             if (view.getId() != id) {
492                 view.setBackgroundColor(Color.TRANSPARENT);
493             }
494         }
495     }
496     public void onAccountSummaryClicked(View view) {
497         b.drawerLayout.closeDrawers();
498
499         showAccountSummaryFragment();
500     }
501     private void showAccountSummaryFragment() {
502         b.mainPager.setCurrentItem(0, true);
503         mainModel.getAccountFilter()
504                  .setValue(null);
505     }
506     public void onLatestTransactionsClicked(View view) {
507         b.drawerLayout.closeDrawers();
508
509         showTransactionsFragment(null);
510     }
511     public void showTransactionsFragment(String accName) {
512         mainModel.getAccountFilter()
513                  .setValue(accName);
514         b.mainPager.setCurrentItem(1, true);
515     }
516     public void showAccountTransactions(String accountName) {
517         mBackMeansToAccountList = true;
518         showTransactionsFragment(accountName);
519     }
520     @Override
521     public void onBackPressed() {
522         if (b.drawerLayout.isDrawerOpen(GravityCompat.START)) {
523             b.drawerLayout.closeDrawer(GravityCompat.START);
524         }
525         else {
526             if (mBackMeansToAccountList && (b.mainPager.getCurrentItem() == 1)) {
527                 mainModel.getAccountFilter()
528                          .setValue(null);
529                 showAccountSummaryFragment();
530                 mBackMeansToAccountList = false;
531             }
532             else {
533                 Logger.debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
534                         getSupportFragmentManager().getBackStackEntryCount()));
535
536                 super.onBackPressed();
537             }
538         }
539     }
540     public void updateLastUpdateTextFromDB() {
541         if (profile == null)
542             return;
543
544         DB.get()
545           .getOptionDAO()
546           .load(profile.getId(), MLDB.OPT_LAST_SCRAPE)
547           .observe(this, opt -> {
548               long lastUpdate = 0;
549               if (opt != null) {
550                   try {
551                       lastUpdate = Long.parseLong(opt.getValue());
552                   }
553                   catch (NumberFormatException ex) {
554                       Logger.debug(TAG, String.format("Error parsing '%s' as long", opt.getValue()),
555                               ex);
556                   }
557               }
558
559               if (lastUpdate == 0) {
560                   Data.lastUpdateDate.postValue(null);
561               }
562               else {
563                   Data.lastUpdateDate.postValue(new Date(lastUpdate));
564               }
565
566               scheduleDataRetrievalIfStale(lastUpdate);
567           });
568     }
569     private void refreshLastUpdateInfo() {
570         final int formatFlags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR |
571                                 DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_NUMERIC_DATE;
572         String templateForTransactions =
573                 getResources().getString(R.string.transaction_count_summary);
574         String templateForAccounts = getResources().getString(R.string.account_count_summary);
575         Integer accountCount = Data.lastUpdateAccountCount.getValue();
576         Integer transactionCount = Data.lastUpdateTransactionCount.getValue();
577         Date lastUpdate = Data.lastUpdateDate.getValue();
578         if (lastUpdate == null) {
579             Data.lastTransactionsUpdateText.setValue("----");
580             Data.lastAccountsUpdateText.setValue("----");
581         }
582         else {
583             Data.lastTransactionsUpdateText.setValue(
584                     String.format(Objects.requireNonNull(Data.locale.getValue()),
585                             templateForTransactions,
586                             transactionCount == null ? 0 : transactionCount,
587                             DateUtils.formatDateTime(this, lastUpdate.getTime(), formatFlags)));
588             Data.lastAccountsUpdateText.setValue(
589                     String.format(Objects.requireNonNull(Data.locale.getValue()),
590                             templateForAccounts, accountCount == null ? 0 : accountCount,
591                             DateUtils.formatDateTime(this, lastUpdate.getTime(), formatFlags)));
592         }
593     }
594     public void onStopTransactionRefreshClick(View view) {
595         Logger.debug("interactive", "Cancelling transactions refresh");
596         mainModel.stopTransactionsRetrieval();
597         b.transactionListCancelDownload.setEnabled(false);
598     }
599     public void onRetrieveRunningChanged(Boolean running) {
600         if (running) {
601             b.transactionListCancelDownload.setEnabled(true);
602             ColorStateList csl = Colors.getColorStateList();
603             b.transactionListProgressBar.setIndeterminateTintList(csl);
604             b.transactionListProgressBar.setProgressTintList(csl);
605             b.transactionListProgressBar.setIndeterminate(true);
606             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
607                 b.transactionListProgressBar.setProgress(0, false);
608             }
609             else {
610                 b.transactionListProgressBar.setProgress(0);
611             }
612             b.transactionProgressLayout.setVisibility(View.VISIBLE);
613         }
614         else {
615             b.transactionProgressLayout.setVisibility(View.GONE);
616         }
617     }
618     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
619         if (progress.getState() == RetrieveTransactionsTask.ProgressState.FINISHED) {
620             Logger.debug("progress", "Done");
621             b.transactionProgressLayout.setVisibility(View.GONE);
622
623             mainModel.transactionRetrievalDone();
624
625             String error = progress.getError();
626             if (error != null) {
627                 if (error.equals(RetrieveTransactionsTask.Result.ERR_JSON_PARSER_ERROR))
628                     error = getResources().getString(R.string.err_json_parser_error);
629
630                 AlertDialog.Builder builder = new AlertDialog.Builder(this);
631                 builder.setMessage(error);
632                 builder.setPositiveButton(R.string.btn_profile_options, (dialog, which) -> {
633                     Logger.debug("error", "will start profile editor");
634                     ProfileDetailActivity.start(this, profile);
635                 });
636                 builder.create()
637                        .show();
638                 return;
639             }
640
641             return;
642         }
643
644
645         b.transactionListCancelDownload.setEnabled(true);
646 //        ColorStateList csl = Colors.getColorStateList();
647 //        progressBar.setIndeterminateTintList(csl);
648 //        progressBar.setProgressTintList(csl);
649 //        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
650 //            progressBar.setProgress(0, false);
651 //        else
652 //            progressBar.setProgress(0);
653         b.transactionProgressLayout.setVisibility(View.VISIBLE);
654
655         if (progress.isIndeterminate() || (progress.getTotal() <= 0)) {
656             b.transactionListProgressBar.setIndeterminate(true);
657             Logger.debug("progress", "indeterminate");
658         }
659         else {
660             if (b.transactionListProgressBar.isIndeterminate()) {
661                 b.transactionListProgressBar.setIndeterminate(false);
662             }
663 //            Logger.debug("progress",
664 //                    String.format(Locale.US, "%d/%d", progress.getProgress(), progress.getTotal
665 //                    ()));
666             b.transactionListProgressBar.setMax(progress.getTotal());
667             // for some reason animation doesn't work - no progress is shown (stick at 0)
668             // on lineageOS 14.1 (Nougat, 7.1.2)
669             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
670                 b.transactionListProgressBar.setProgress(progress.getProgress(), false);
671             else
672                 b.transactionListProgressBar.setProgress(progress.getProgress());
673         }
674     }
675     public void fabShouldShow() {
676         if ((profile != null) && profile.permitPosting() && !b.drawerLayout.isOpen())
677             fabManager.showFab();
678     }
679     @Override
680     public Context getContext() {
681         return this;
682     }
683     @Override
684     public void showManagedFab() {
685         fabShouldShow();
686     }
687     @Override
688     public void hideManagedFab() {
689         fabManager.hideFab();
690     }
691     public static class SectionsPagerAdapter extends FragmentStateAdapter {
692
693         public SectionsPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
694             super(fragmentActivity);
695         }
696         @NotNull
697         @Override
698         public Fragment createFragment(int position) {
699             Logger.debug("main",
700                     String.format(Locale.ENGLISH, "Switching to fragment %d", position));
701             switch (position) {
702                 case 0:
703 //                    debug("flow", "Creating account summary fragment");
704                     return new AccountSummaryFragment();
705                 case 1:
706                     return new TransactionListFragment();
707                 default:
708                     throw new IllegalStateException(
709                             String.format("Unexpected fragment index: " + "%d", position));
710             }
711         }
712
713         @Override
714         public int getItemCount() {
715             return 2;
716         }
717     }
718 }