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