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