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