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