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