]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
replace in-activity copy of account name filter value with the global item in Data
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / MainActivity.java
1 /*
2  * Copyright © 2019 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.SharedPreferences;
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.AsyncTask;
29 import android.os.Build;
30 import android.os.Bundle;
31 import android.util.Log;
32 import android.view.View;
33 import android.view.ViewGroup;
34 import android.view.ViewPropertyAnimator;
35 import android.view.animation.AnimationUtils;
36 import android.widget.LinearLayout;
37 import android.widget.ProgressBar;
38 import android.widget.TextView;
39 import android.widget.Toast;
40
41 import com.google.android.material.floatingactionbutton.FloatingActionButton;
42
43 import net.ktnx.mobileledger.R;
44 import net.ktnx.mobileledger.async.DbOpQueue;
45 import net.ktnx.mobileledger.async.RefreshDescriptionsTask;
46 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
47 import net.ktnx.mobileledger.model.Data;
48 import net.ktnx.mobileledger.model.LedgerAccount;
49 import net.ktnx.mobileledger.model.MobileLedgerProfile;
50 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryAdapter;
51 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
52 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryViewModel;
53 import net.ktnx.mobileledger.ui.profiles.ProfileDetailFragment;
54 import net.ktnx.mobileledger.ui.profiles.ProfilesRecyclerViewAdapter;
55 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
56 import net.ktnx.mobileledger.ui.transaction_list.TransactionListViewModel;
57 import net.ktnx.mobileledger.utils.Colors;
58 import net.ktnx.mobileledger.utils.GetOptCallback;
59 import net.ktnx.mobileledger.utils.LockHolder;
60 import net.ktnx.mobileledger.utils.MLDB;
61
62 import org.jetbrains.annotations.NotNull;
63
64 import java.text.DateFormat;
65 import java.util.ArrayList;
66 import java.util.Date;
67 import java.util.List;
68 import java.util.Locale;
69
70 import androidx.appcompat.app.ActionBarDrawerToggle;
71 import androidx.appcompat.widget.Toolbar;
72 import androidx.core.view.GravityCompat;
73 import androidx.drawerlayout.widget.DrawerLayout;
74 import androidx.fragment.app.Fragment;
75 import androidx.fragment.app.FragmentManager;
76 import androidx.fragment.app.FragmentPagerAdapter;
77 import androidx.recyclerview.widget.LinearLayoutManager;
78 import androidx.recyclerview.widget.RecyclerView;
79 import androidx.viewpager.widget.ViewPager;
80
81 import static net.ktnx.mobileledger.utils.Logger.debug;
82
83 public class MainActivity extends ProfileThemedActivity {
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 String PREF_THEME_ID = "themeId";
88     public AccountSummaryFragment mAccountSummaryFragment;
89     DrawerLayout drawer;
90     private View profileListHeadMore, profileListHeadCancel, profileListHeadAddProfile;
91     private View bTransactionListCancelDownload;
92     private SectionsPagerAdapter mSectionsPagerAdapter;
93     private ViewPager mViewPager;
94     private FloatingActionButton fab;
95     private ProfilesRecyclerViewAdapter mProfileListAdapter;
96     private int mCurrentPage;
97     private boolean mBackMeansToAccountList = false;
98     private Toolbar mToolbar;
99     private DrawerLayout.SimpleDrawerListener drawerListener;
100     private ActionBarDrawerToggle barDrawerToggle;
101     private ViewPager.SimpleOnPageChangeListener pageChangeListener;
102     private MobileLedgerProfile profile;
103     @Override
104     protected void onStart() {
105         super.onStart();
106
107         mViewPager.setCurrentItem(mCurrentPage, false);
108     }
109     @Override
110     protected void onSaveInstanceState(@NotNull Bundle outState) {
111         super.onSaveInstanceState(outState);
112         outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
113         if (Data.accountFilter.getValue() != null)
114             outState.putString(STATE_ACC_FILTER, Data.accountFilter.getValue());
115     }
116     @Override
117     protected void onDestroy() {
118         mSectionsPagerAdapter = null;
119         RecyclerView root = findViewById(R.id.nav_profile_list);
120         if (root != null) root.setAdapter(null);
121         if (drawer != null) drawer.removeDrawerListener(drawerListener);
122         drawerListener = null;
123         if (drawer != null) drawer.removeDrawerListener(barDrawerToggle);
124         barDrawerToggle = null;
125         if (mViewPager != null) mViewPager.removeOnPageChangeListener(pageChangeListener);
126         pageChangeListener = null;
127         super.onDestroy();
128     }
129     @Override
130     protected void setupProfileColors() {
131         SharedPreferences prefs = getPreferences(MODE_PRIVATE);
132         int profileColor = prefs.getInt(PREF_THEME_ID, -2);
133         if (profileColor == -2) profileColor = Data.retrieveCurrentThemeIdFromDb();
134         Colors.setupTheme(this, profileColor);
135         Colors.profileThemeId = profileColor;
136         storeThemeIdInPrefs(profileColor);
137     }
138     @Override
139     protected void onResume() {
140         super.onResume();
141         fabShouldShow();
142     }
143     @Override
144     protected void onCreate(Bundle savedInstanceState) {
145         super.onCreate(savedInstanceState);
146         debug("flow", "MainActivity.onCreate()");
147         setContentView(R.layout.activity_main);
148
149         fab = findViewById(R.id.btn_add_transaction);
150         profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
151         profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
152         LinearLayout profileListHeadMoreAndCancel =
153                 findViewById(R.id.nav_profile_list_head_buttons);
154         profileListHeadAddProfile = findViewById(R.id.nav_new_profile_button);
155         drawer = findViewById(R.id.drawer_layout);
156         bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
157         mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
158         mViewPager = findViewById(R.id.root_frame);
159
160         Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
161         if (extra != null && savedInstanceState == null) savedInstanceState = extra;
162
163
164         mToolbar = findViewById(R.id.toolbar);
165         setSupportActionBar(mToolbar);
166
167         Data.profile.observe(this, this::onProfileChanged);
168
169         Data.profiles.observe(this, this::onProfileListChanged);
170
171         if (barDrawerToggle == null) {
172             barDrawerToggle = new ActionBarDrawerToggle(this, drawer, mToolbar,
173                     R.string.navigation_drawer_open, R.string.navigation_drawer_close);
174             drawer.addDrawerListener(barDrawerToggle);
175         }
176         barDrawerToggle.syncState();
177
178         TextView ver = drawer.findViewById(R.id.drawer_version_text);
179
180         try {
181             PackageInfo pi =
182                     getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
183             ver.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 (pageChangeListener == null) {
194             pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
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.addOnPageChangeListener(pageChangeListener);
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             Data.accountFilter.setValue(savedInstanceState.getString(STATE_ACC_FILTER, null));
223         }
224
225         Data.lastUpdateDate.observe(this, this::updateLastUpdateDisplay);
226
227         findViewById(R.id.btn_no_profiles_add)
228                 .setOnClickListener(v -> startEditProfileActivity(null));
229
230         findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
231
232         findViewById(R.id.nav_new_profile_button)
233                 .setOnClickListener(v -> startEditProfileActivity(null));
234
235         RecyclerView root = findViewById(R.id.nav_profile_list);
236         if (root == null)
237             throw new RuntimeException("Can't get hold on the transaction value view");
238
239         if (mProfileListAdapter == null) mProfileListAdapter = new ProfilesRecyclerViewAdapter();
240         root.setAdapter(mProfileListAdapter);
241
242         mProfileListAdapter.editingProfiles.observe(this, newValue -> {
243             if (newValue) {
244                 profileListHeadMore.setVisibility(View.GONE);
245                 profileListHeadCancel.setVisibility(View.VISIBLE);
246                 profileListHeadAddProfile.setVisibility(View.VISIBLE);
247                 if (drawer.isDrawerOpen(GravityCompat.START)) {
248                     profileListHeadMore.startAnimation(
249                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
250                     profileListHeadCancel.startAnimation(
251                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
252                     profileListHeadAddProfile.startAnimation(
253                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
254                 }
255             }
256             else {
257                 profileListHeadCancel.setVisibility(View.GONE);
258                 profileListHeadMore.setVisibility(View.VISIBLE);
259                 profileListHeadAddProfile.setVisibility(View.GONE);
260                 if (drawer.isDrawerOpen(GravityCompat.START)) {
261                     profileListHeadCancel.startAnimation(
262                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
263                     profileListHeadMore.startAnimation(
264                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
265                     profileListHeadAddProfile.startAnimation(
266                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
267                 }
268             }
269
270             mProfileListAdapter.notifyDataSetChanged();
271         });
272
273         LinearLayoutManager llm = new LinearLayoutManager(this);
274
275         llm.setOrientation(RecyclerView.VERTICAL);
276         root.setLayoutManager(llm);
277
278         profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
279         profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
280         profileListHeadMoreAndCancel
281                 .setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
282         if (drawerListener == null) {
283             drawerListener = new DrawerLayout.SimpleDrawerListener() {
284                 @Override
285                 public void onDrawerClosed(View drawerView) {
286                     super.onDrawerClosed(drawerView);
287                     mProfileListAdapter.setAnimationsEnabled(false);
288                     mProfileListAdapter.editingProfiles.setValue(false);
289                 }
290                 @Override
291                 public void onDrawerOpened(View drawerView) {
292                     super.onDrawerOpened(drawerView);
293                     mProfileListAdapter.setAnimationsEnabled(true);
294                 }
295             };
296             drawer.addDrawerListener(drawerListener);
297         }
298         setupProfile();
299     }
300     private void scheduleDataRetrievalIfStale(Date lastUpdate) {
301         long now = new Date().getTime();
302         if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
303             if (lastUpdate == null) debug("db::", "WEB data never fetched. scheduling a fetch");
304             else debug("db", String.format(Locale.ENGLISH,
305                     "WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
306                     lastUpdate.getTime() / 1000f, now / 1000f));
307
308             Data.scheduleTransactionListRetrieval(this);
309         }
310     }
311     private void createShortcuts(List<MobileLedgerProfile> list) {
312         if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return;
313
314         List<ShortcutInfo> shortcuts = new ArrayList<>();
315         int i = 0;
316         for (MobileLedgerProfile p : list) {
317             if (!p.isPostingPermitted()) continue;
318
319             ShortcutInfo si = new ShortcutInfo.Builder(this, "new_transaction_" + p.getUuid())
320                     .setShortLabel(p.getName())
321                     .setIcon(Icon.createWithResource(this, R.drawable.svg_thick_plus_white))
322                     .setIntent(
323                             new Intent(Intent.ACTION_VIEW, null, this, NewTransactionActivity.class)
324                                     .putExtra("profile_uuid", p.getUuid())).setRank(i).build();
325             shortcuts.add(si);
326             i++;
327         }
328         ShortcutManager sm = getSystemService(ShortcutManager.class);
329         sm.setDynamicShortcuts(shortcuts);
330     }
331     private void onProfileListChanged(List<MobileLedgerProfile> newList) {
332         if (newList == null) {
333             // profiles not yet loaded from DB
334             findViewById(R.id.loading_layout).setVisibility(View.VISIBLE);
335             findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
336             findViewById(R.id.pager_layout).setVisibility(View.GONE);
337             return;
338         }
339
340         if (newList.isEmpty()) {
341             findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
342             findViewById(R.id.pager_layout).setVisibility(View.GONE);
343             findViewById(R.id.loading_layout).setVisibility(View.GONE);
344             return;
345         }
346
347         findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
348         findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
349         findViewById(R.id.loading_layout).setVisibility(View.GONE);
350
351         findViewById(R.id.nav_profile_list).setMinimumHeight(
352                 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
353
354         debug("profiles", "profile list changed");
355         mProfileListAdapter.notifyDataSetChanged();
356
357         createShortcuts(newList);
358     }
359     /**
360      * called when the current profile has changed
361      */
362     private void onProfileChanged(MobileLedgerProfile profile) {
363         boolean haveProfile = profile != null;
364         findViewById(R.id.no_profiles_layout).setVisibility(haveProfile ? View.GONE : View.VISIBLE);
365         findViewById(R.id.pager_layout).setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
366
367         if (haveProfile) setTitle(profile.getName());
368         else setTitle(R.string.app_name);
369
370         this.profile = profile;
371
372         mProfileListAdapter.notifyDataSetChanged();
373
374         int newProfileTheme = haveProfile ? profile.getThemeId() : -1;
375         if (newProfileTheme != Colors.profileThemeId) {
376             debug("profiles",
377                     String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
378                             newProfileTheme));
379             MainActivity.this.profileThemeChanged();
380             Colors.profileThemeId = newProfileTheme;
381             // profileThemeChanged would restart the activity, so no need to reload the
382             // data sets below
383             return;
384         }
385
386         drawer.closeDrawers();
387
388         Data.transactions.clear();
389         debug("transactions", "requesting list reload");
390         TransactionListViewModel.scheduleTransactionListReload();
391
392         Data.accounts.clear();
393         AccountSummaryViewModel.scheduleAccountListReload();
394
395         if (haveProfile) {
396             if (profile.isPostingPermitted()) {
397                 mToolbar.setSubtitle(null);
398                 fab.show();
399             }
400             else {
401                 mToolbar.setSubtitle(R.string.profile_subitlte_read_only);
402                 fab.hide();
403             }
404         }
405         else {
406             mToolbar.setSubtitle(null);
407             fab.hide();
408         }
409
410         updateLastUpdateTextFromDB();
411     }
412     private void updateLastUpdateDisplay(Date newValue) {
413         LinearLayout l = findViewById(R.id.transactions_last_update_layout);
414         TextView v = findViewById(R.id.transactions_last_update);
415         if (newValue == null) {
416             l.setVisibility(View.INVISIBLE);
417             debug("main", "no last update date :(");
418         }
419         else {
420             final String text = DateFormat.getDateTimeInstance().format(newValue);
421             v.setText(text);
422             l.setVisibility(View.VISIBLE);
423             debug("main", String.format("Date formatted: %s", text));
424         }
425
426         scheduleDataRetrievalIfStale(newValue);
427     }
428     private void profileThemeChanged() {
429         Bundle bundle = new Bundle();
430         onSaveInstanceState(bundle);
431
432         storeThemeIdInPrefs(profile.getThemeId());
433
434         // restart activity to reflect theme change
435         finish();
436
437         // un-hook all observed LiveData
438         Data.profile.removeObservers(this);
439         Data.profiles.removeObservers(this);
440         Data.lastUpdateDate.removeObservers(this);
441         Intent intent = new Intent(this, this.getClass());
442         intent.putExtra(BUNDLE_SAVED_STATE, bundle);
443         startActivity(intent);
444     }
445     private void storeThemeIdInPrefs(int themeId) {
446         // store the new theme id in the preferences
447         SharedPreferences prefs = getPreferences(MODE_PRIVATE);
448         SharedPreferences.Editor e = prefs.edit();
449         e.putInt(PREF_THEME_ID, themeId);
450         e.apply();
451     }
452     public void startEditProfileActivity(MobileLedgerProfile profile) {
453         Intent intent = new Intent(this, ProfileDetailActivity.class);
454         Bundle args = new Bundle();
455         if (profile != null) {
456             int index = Data.getProfileIndex(profile);
457             if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
458         }
459         intent.putExtras(args);
460         startActivity(intent, args);
461     }
462     private void setupProfile() {
463         MLDB.getOption(MLDB.OPT_PROFILE_UUID, null, new GetOptCallback() {
464             @Override
465             protected void onResult(String profileUUID) {
466                 MobileLedgerProfile startupProfile;
467
468                 startupProfile = Data.getProfile(profileUUID);
469                 Data.setCurrentProfile(startupProfile);
470             }
471         });
472     }
473     public void fabNewTransactionClicked(View view) {
474         Intent intent = new Intent(this, NewTransactionActivity.class);
475         startActivity(intent);
476         overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
477     }
478     public void navSettingsClicked(View view) {
479         Intent intent = new Intent(this, SettingsActivity.class);
480         startActivity(intent);
481         drawer.closeDrawers();
482     }
483     public void markDrawerItemCurrent(int id) {
484         TextView item = drawer.findViewById(id);
485         item.setBackgroundColor(Colors.tableRowDarkBG);
486
487         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
488         for (int i = 0; i < actions.getChildCount(); i++) {
489             View view = actions.getChildAt(i);
490             if (view.getId() != id) {
491                 view.setBackgroundColor(Color.TRANSPARENT);
492             }
493         }
494     }
495     public void onAccountSummaryClicked(View view) {
496         drawer.closeDrawers();
497
498         showAccountSummaryFragment();
499     }
500     private void showAccountSummaryFragment() {
501         mViewPager.setCurrentItem(0, true);
502         Data.accountFilter.setValue(null);
503     }
504     public void onLatestTransactionsClicked(View view) {
505         drawer.closeDrawers();
506
507         showTransactionsFragment((String) null);
508     }
509     private void showTransactionsFragment(String accName) {
510         Data.accountFilter.setValue(accName);
511         mViewPager.setCurrentItem(1, true);
512     }
513     private void showTransactionsFragment(LedgerAccount account) {
514         showTransactionsFragment((account == null) ? null : account.getName());
515     }
516     public void showAccountTransactions(LedgerAccount account) {
517         mBackMeansToAccountList = true;
518         showTransactionsFragment(account);
519     }
520     @Override
521     public void onBackPressed() {
522         DrawerLayout drawer = findViewById(R.id.drawer_layout);
523         if (drawer.isDrawerOpen(GravityCompat.START)) {
524             drawer.closeDrawer(GravityCompat.START);
525         }
526         else {
527             if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
528                 Data.accountFilter.setValue(null);
529                 showAccountSummaryFragment();
530                 mBackMeansToAccountList = false;
531             }
532             else {
533                 debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
534                         getSupportFragmentManager().getBackStackEntryCount()));
535
536                 super.onBackPressed();
537             }
538         }
539     }
540     public void updateLastUpdateTextFromDB() {
541         if (profile == null) return;
542
543         long last_update = profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
544
545         debug("transactions", String.format(Locale.ENGLISH, "Last update = %d", last_update));
546         if (last_update == 0) {
547             Data.lastUpdateDate.postValue(null);
548         }
549         else {
550             Data.lastUpdateDate.postValue(new Date(last_update));
551         }
552     }
553     public void onStopTransactionRefreshClick(View view) {
554         debug("interactive", "Cancelling transactions refresh");
555         Data.stopTransactionsRetrieval();
556         bTransactionListCancelDownload.setEnabled(false);
557     }
558     public void onRetrieveDone(String error) {
559         Data.transactionRetrievalDone();
560         findViewById(R.id.transaction_progress_layout).setVisibility(View.GONE);
561
562         if (error == null) {
563             updateLastUpdateTextFromDB();
564
565             new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
566             TransactionListViewModel.scheduleTransactionListReload();
567         }
568         else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
569     }
570     public void onRetrieveStart() {
571         ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
572         bTransactionListCancelDownload.setEnabled(true);
573         ColorStateList csl = Colors.getColorStateList();
574         progressBar.setIndeterminateTintList(csl);
575         progressBar.setProgressTintList(csl);
576         progressBar.setIndeterminate(true);
577         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
578         else progressBar.setProgress(0);
579         findViewById(R.id.transaction_progress_layout).setVisibility(View.VISIBLE);
580     }
581     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
582         ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
583         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
584             (progress.getTotal() == 0))
585         {
586             progressBar.setIndeterminate(true);
587         }
588         else {
589             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
590                 progressBar.setMin(0);
591             }
592             progressBar.setMax(progress.getTotal());
593             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
594                 progressBar.setProgress(progress.getProgress(), true);
595             }
596             else progressBar.setProgress(progress.getProgress());
597             progressBar.setIndeterminate(false);
598         }
599     }
600     public void fabShouldShow() {
601         if ((profile != null) && profile.isPostingPermitted()) fab.show();
602     }
603     public void fabHide() {
604         fab.hide();
605     }
606     public void onAccountSummaryRowViewClicked(View view) {
607         ViewGroup row;
608         if (view.getId() == R.id.account_expander) row = (ViewGroup) view.getParent().getParent();
609         else row = (ViewGroup) view.getParent();
610
611         LedgerAccount acc = (LedgerAccount) row.getTag();
612         switch (view.getId()) {
613             case R.id.account_row_acc_name:
614             case R.id.account_expander:
615             case R.id.account_expander_container:
616                 debug("accounts", "Account expander clicked");
617                 if (!acc.hasSubAccounts()) return;
618
619                 boolean wasExpanded = acc.isExpanded();
620
621                 View arrow = row.findViewById(R.id.account_expander_container);
622
623                 arrow.clearAnimation();
624                 ViewPropertyAnimator animator = arrow.animate();
625
626                 acc.toggleExpanded();
627                 DbOpQueue.add("update accounts set expanded=? where name=? and profile=?",
628                         new Object[]{acc.isExpanded(), acc.getName(), profile.getUuid()
629                         });
630
631                 if (wasExpanded) {
632                     debug("accounts", String.format("Collapsing account '%s'", acc.getName()));
633                     arrow.setRotation(0);
634                     animator.rotationBy(180);
635
636                     // removing all child accounts from the view
637                     int start = -1, count = 0;
638                     try (LockHolder ignored = Data.accounts.lockForWriting()) {
639                         for (int i = 0; i < Data.accounts.size(); i++) {
640                             if (acc.isParentOf(Data.accounts.get(i))) {
641 //                                debug("accounts", String.format("Found a child '%s' at position %d",
642 //                                        Data.accounts.get(i).getName(), i));
643                                 if (start == -1) {
644                                     start = i;
645                                 }
646                                 count++;
647                             }
648                             else {
649                                 if (start != -1) {
650 //                                    debug("accounts",
651 //                                            String.format("Found a non-child '%s' at position %d",
652 //                                                    Data.accounts.get(i).getName(), i));
653                                     break;
654                                 }
655                             }
656                         }
657
658                         if (start != -1) {
659                             for (int j = 0; j < count; j++) {
660 //                                debug("accounts", String.format("Removing item %d: %s", start + j,
661 //                                        Data.accounts.get(start).getName()));
662                                 Data.accounts.removeQuietly(start);
663                             }
664
665                             mAccountSummaryFragment.modelAdapter
666                                     .notifyItemRangeRemoved(start, count);
667                         }
668                     }
669                 }
670                 else {
671                     debug("accounts", String.format("Expanding account '%s'", acc.getName()));
672                     arrow.setRotation(180);
673                     animator.rotationBy(-180);
674                     List<LedgerAccount> children = profile.loadVisibleChildAccountsOf(acc);
675                     try (LockHolder ignored = Data.accounts.lockForWriting()) {
676                         int parentPos = Data.accounts.indexOf(acc);
677                         if (parentPos != -1) {
678                             // may have disappeared in a concurrent refresh operation
679                             Data.accounts.addAllQuietly(parentPos + 1, children);
680                             mAccountSummaryFragment.modelAdapter
681                                     .notifyItemRangeInserted(parentPos + 1, children.size());
682                         }
683                     }
684                 }
685                 break;
686             case R.id.account_row_acc_amounts:
687                 if (acc.getAmountCount() > AccountSummaryAdapter.AMOUNT_LIMIT) {
688                     acc.toggleAmountsExpanded();
689                     DbOpQueue
690                             .add("update accounts set amounts_expanded=? where name=? and profile=?",
691                                     new Object[]{acc.amountsExpanded(), acc.getName(),
692                                                  profile.getUuid()
693                                     });
694                     Data.accounts.triggerItemChangedNotification(acc);
695                 }
696                 break;
697         }
698     }
699
700     public class SectionsPagerAdapter extends FragmentPagerAdapter {
701
702         SectionsPagerAdapter(FragmentManager fm) {
703             super(fm);
704         }
705
706         @NotNull
707         @Override
708         public Fragment getItem(int position) {
709             debug("main", String.format(Locale.ENGLISH, "Switching to fragment %d", position));
710             switch (position) {
711                 case 0:
712 //                    debug("flow", "Creating account summary fragment");
713                     return mAccountSummaryFragment = new AccountSummaryFragment();
714                 case 1:
715                     return new TransactionListFragment();
716                 default:
717                     throw new IllegalStateException(
718                             String.format("Unexpected fragment index: " + "%d", position));
719             }
720         }
721
722         @Override
723         public int getCount() {
724             return 2;
725         }
726     }
727 }