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