]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
store/retrieve account name filter in the bundle
[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.pm.PackageInfo;
22 import android.content.res.ColorStateList;
23 import android.graphics.Color;
24 import android.os.AsyncTask;
25 import android.os.Build;
26 import android.os.Bundle;
27 import android.util.Log;
28 import android.view.View;
29 import android.view.ViewGroup;
30 import android.view.ViewPropertyAnimator;
31 import android.view.animation.Animation;
32 import android.view.animation.AnimationUtils;
33 import android.widget.LinearLayout;
34 import android.widget.ProgressBar;
35 import android.widget.TextView;
36 import android.widget.Toast;
37
38 import com.google.android.material.floatingactionbutton.FloatingActionButton;
39
40 import net.ktnx.mobileledger.R;
41 import net.ktnx.mobileledger.async.DbOpQueue;
42 import net.ktnx.mobileledger.async.RefreshDescriptionsTask;
43 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
44 import net.ktnx.mobileledger.model.Data;
45 import net.ktnx.mobileledger.model.LedgerAccount;
46 import net.ktnx.mobileledger.model.MobileLedgerProfile;
47 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryAdapter;
48 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
49 import net.ktnx.mobileledger.ui.profiles.ProfileDetailFragment;
50 import net.ktnx.mobileledger.ui.profiles.ProfilesRecyclerViewAdapter;
51 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
52 import net.ktnx.mobileledger.ui.transaction_list.TransactionListViewModel;
53 import net.ktnx.mobileledger.utils.Colors;
54 import net.ktnx.mobileledger.utils.LockHolder;
55 import net.ktnx.mobileledger.utils.MLDB;
56
57 import java.lang.ref.WeakReference;
58 import java.text.DateFormat;
59 import java.util.Date;
60 import java.util.List;
61 import java.util.Observable;
62 import java.util.Observer;
63
64 import androidx.appcompat.app.ActionBarDrawerToggle;
65 import androidx.appcompat.widget.Toolbar;
66 import androidx.core.view.GravityCompat;
67 import androidx.drawerlayout.widget.DrawerLayout;
68 import androidx.fragment.app.Fragment;
69 import androidx.fragment.app.FragmentManager;
70 import androidx.fragment.app.FragmentPagerAdapter;
71 import androidx.recyclerview.widget.LinearLayoutManager;
72 import androidx.recyclerview.widget.RecyclerView;
73 import androidx.viewpager.widget.ViewPager;
74
75 public class MainActivity extends ProfileThemedActivity {
76     public static final String STATE_CURRENT_PAGE = "current_page";
77     public static final String BUNDLE_SAVED_STATE = "bundle_savedState";
78     public static final String STATE_ACC_FILTER = "account_filter";
79     public AccountSummaryFragment mAccountSummaryFragment;
80     DrawerLayout drawer;
81     private LinearLayout profileListContainer;
82     private View profileListHeadArrow, profileListHeadMore, profileListHeadCancel;
83     private LinearLayout profileListHeadMoreAndCancel;
84     private FragmentManager fragmentManager;
85     private TextView tvLastUpdate;
86     private RetrieveTransactionsTask retrieveTransactionsTask;
87     private View bTransactionListCancelDownload;
88     private ProgressBar progressBar;
89     private LinearLayout progressLayout;
90     private SectionsPagerAdapter mSectionsPagerAdapter;
91     private ViewPager mViewPager;
92     private FloatingActionButton fab;
93     private boolean profileModificationEnabled = false;
94     private boolean profileListExpanded = false;
95     private ProfilesRecyclerViewAdapter mProfileListAdapter;
96     private int mCurrentPage;
97     private String mAccountFilter;
98     @Override
99     protected void onStart() {
100         super.onStart();
101
102         setupProfile();
103
104         updateLastUpdateTextFromDB();
105         Date lastUpdate = Data.lastUpdateDate.get();
106
107         long now = new Date().getTime();
108         if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
109             if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
110             else Log.d("db",
111                     String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
112                             lastUpdate.getTime() / 1000f, now / 1000f));
113
114             scheduleTransactionListRetrieval();
115         }
116
117         mViewPager.setCurrentItem(mCurrentPage, false);
118         if (mAccountFilter != null) showTransactionsFragment(mAccountFilter);
119
120     }
121     @Override
122     protected void onSaveInstanceState(Bundle outState) {
123         super.onSaveInstanceState(outState);
124         outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
125         if (TransactionListFragment.accountFilter.get() != null)
126             outState.putString(STATE_ACC_FILTER, TransactionListFragment.accountFilter.get());
127     }
128     @Override
129     protected void onCreate(Bundle savedInstanceState) {
130         super.onCreate(savedInstanceState);
131
132         setContentView(R.layout.activity_main);
133
134         fab = findViewById(R.id.btn_add_transaction);
135         profileListContainer = findViewById(R.id.nav_profile_list_container);
136         profileListHeadArrow = findViewById(R.id.nav_profiles_arrow);
137         profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
138         profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
139         profileListHeadMoreAndCancel = findViewById(R.id.nav_profile_list_head_buttons);
140         drawer = findViewById(R.id.drawer_layout);
141         tvLastUpdate = findViewById(R.id.transactions_last_update);
142         bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
143         progressBar = findViewById(R.id.transaction_list_progress_bar);
144         progressLayout = findViewById(R.id.transaction_progress_layout);
145         fragmentManager = getSupportFragmentManager();
146         mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
147         mViewPager = findViewById(R.id.root_frame);
148
149         Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
150         if (extra != null && savedInstanceState == null) savedInstanceState = extra;
151
152
153         Toolbar toolbar = findViewById(R.id.toolbar);
154         setSupportActionBar(toolbar);
155
156         Data.profile.addObserver((o, arg) -> {
157             MobileLedgerProfile profile = Data.profile.get();
158             runOnUiThread(() -> {
159                 if (profile == null) setTitle(R.string.app_name);
160                 else setTitle(profile.getName());
161                 updateLastUpdateTextFromDB();
162                 if (profile.isPostingPermitted()) {
163                     toolbar.setSubtitle(null);
164                     fab.show();
165                 }
166                 else {
167                     toolbar.setSubtitle(R.string.profile_subitlte_read_only);
168                     fab.hide();
169                 }
170
171                 int newProfileTheme = profile.getThemeId();
172                 if (newProfileTheme != Colors.profileThemeId) {
173                     Log.d("profiles", String.format("profile theme %d → %d", Colors.profileThemeId,
174                             newProfileTheme));
175                     profileThemeChanged();
176                     Colors.profileThemeId = newProfileTheme;
177                 }
178             });
179         });
180         Data.profiles.addObserver((o, arg) -> {
181             findViewById(R.id.nav_profile_list).setMinimumHeight(
182                     (int) (getResources().getDimension(R.dimen.thumb_row_height) *
183                            Data.profiles.size()));
184             mProfileListAdapter.notifyDataSetChanged();
185         });
186
187         ActionBarDrawerToggle toggle =
188                 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
189                         R.string.navigation_drawer_close);
190         drawer.addDrawerListener(toggle);
191         toggle.syncState();
192
193         TextView ver = drawer.findViewById(R.id.drawer_version_text);
194
195         try {
196             PackageInfo pi =
197                     getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
198             ver.setText(pi.versionName);
199         }
200         catch (Exception e) {
201             e.printStackTrace();
202         }
203
204         if (progressBar == null)
205             throw new RuntimeException("Can't get hold on the transaction value progress bar");
206         if (progressLayout == null) throw new RuntimeException(
207                 "Can't get hold on the transaction value progress bar layout");
208
209         markDrawerItemCurrent(R.id.nav_account_summary);
210
211         mViewPager.setAdapter(mSectionsPagerAdapter);
212         mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
213             @Override
214             public void onPageSelected(int 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", String.format("Unexpected page index %d", position));
224                 }
225
226                 super.onPageSelected(position);
227             }
228         });
229
230         mCurrentPage = 0;
231         if (savedInstanceState != null) {
232             int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
233             if (currentPage != -1) {
234                 mCurrentPage = currentPage;
235             }
236             mAccountFilter = savedInstanceState.getString(STATE_ACC_FILTER, null);
237         }
238
239         Data.lastUpdateDate.addObserver((o, arg) -> {
240             Log.d("main", "lastUpdateDate changed");
241             runOnUiThread(this::updateLastUpdateDisplay);
242         });
243
244         updateLastUpdateDisplay();
245
246         findViewById(R.id.btn_no_profiles_add)
247                 .setOnClickListener(v -> startEditProfileActivity(null));
248
249         findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
250
251         findViewById(R.id.nav_new_profile_button)
252                 .setOnClickListener(v -> startEditProfileActivity(null));
253
254         RecyclerView root = findViewById(R.id.nav_profile_list);
255         if (root == null)
256             throw new RuntimeException("Can't get hold on the transaction value view");
257
258         mProfileListAdapter = new ProfilesRecyclerViewAdapter();
259         root.setAdapter(mProfileListAdapter);
260
261         mProfileListAdapter.addEditingProfilesObserver(new Observer() {
262             @Override
263             public void update(Observable o, Object arg) {
264                 if (mProfileListAdapter.isEditingProfiles()) {
265                     profileListHeadArrow.clearAnimation();
266                     profileListHeadArrow.setVisibility(View.GONE);
267                     profileListHeadMore.setVisibility(View.GONE);
268                     profileListHeadCancel.setVisibility(View.VISIBLE);
269                 }
270                 else {
271                     profileListHeadArrow.setRotation(180f);
272                     profileListHeadArrow.setVisibility(View.VISIBLE);
273                     profileListHeadCancel.setVisibility(View.GONE);
274                     profileListHeadMore.setVisibility(View.GONE);
275                     profileListHeadMore
276                             .setVisibility(profileListExpanded ? View.VISIBLE : View.GONE);
277                 }
278             }
279         });
280
281         LinearLayoutManager llm = new LinearLayoutManager(this);
282
283         llm.setOrientation(RecyclerView.VERTICAL);
284         root.setLayoutManager(llm);
285
286         profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
287         profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
288         profileListHeadMoreAndCancel
289                 .setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
290
291         drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
292             @Override
293             public void onDrawerClosed(View drawerView) {
294                 super.onDrawerClosed(drawerView);
295                 collapseProfileList();
296             }
297         });
298     }
299     private void updateLastUpdateDisplay() {
300         TextView v = findViewById(R.id.transactions_last_update);
301         Date date = Data.lastUpdateDate.get();
302         if (date == null) {
303             v.setText(R.string.transaction_last_update_never);
304             Log.d("main", "no last update date :(");
305         }
306         else {
307             final String text = DateFormat.getDateTimeInstance().format(date);
308             v.setText(text);
309             Log.d("main", String.format("Date formatted: %s", text));
310         }
311     }
312     private void profileThemeChanged() {
313         setupProfileColors();
314
315         Bundle bundle = new Bundle();
316         onSaveInstanceState(bundle);
317         // restart activity to reflect theme change
318         finish();
319         Intent intent = new Intent(this, this.getClass());
320         intent.putExtra(BUNDLE_SAVED_STATE, bundle);
321         startActivity(intent);
322     }
323     public void startEditProfileActivity(MobileLedgerProfile profile) {
324         Intent intent = new Intent(this, ProfileDetailActivity.class);
325         Bundle args = new Bundle();
326         if (profile != null) {
327             int index = Data.getProfileIndex(profile);
328             if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
329         }
330         intent.putExtras(args);
331         startActivity(intent, args);
332     }
333     private void setupProfile() {
334         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
335         MobileLedgerProfile profile;
336
337         profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
338
339         if (Data.profiles.isEmpty()) {
340             findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
341             findViewById(R.id.pager_layout).setVisibility(View.GONE);
342             return;
343         }
344
345         findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
346         findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
347
348         if (profile == null) profile = Data.profiles.get(0);
349
350         if (profile == null) throw new AssertionError("profile must have a value");
351
352         Data.setCurrentProfile(profile);
353     }
354     public void fabNewTransactionClicked(View view) {
355         Intent intent = new Intent(this, NewTransactionActivity.class);
356         startActivity(intent);
357         overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
358     }
359     public void navSettingsClicked(View view) {
360         Intent intent = new Intent(this, SettingsActivity.class);
361         startActivity(intent);
362         drawer.closeDrawers();
363     }
364     public void markDrawerItemCurrent(int id) {
365         TextView item = drawer.findViewById(id);
366         item.setBackgroundColor(Colors.tableRowDarkBG);
367
368         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
369         for (int i = 0; i < actions.getChildCount(); i++) {
370             View view = actions.getChildAt(i);
371             if (view.getId() != id) {
372                 view.setBackgroundColor(Color.TRANSPARENT);
373             }
374         }
375     }
376     public void onAccountSummaryClicked(View view) {
377         drawer.closeDrawers();
378
379         showAccountSummaryFragment();
380     }
381     private void showAccountSummaryFragment() {
382         mViewPager.setCurrentItem(0, true);
383         TransactionListFragment.accountFilter.set(null);
384 //        FragmentTransaction ft = fragmentManager.beginTransaction();
385 //        accountSummaryFragment = new AccountSummaryFragment();
386 //        ft.replace(R.id.root_frame, accountSummaryFragment);
387 //        ft.commit();
388 //        currentFragment = accountSummaryFragment;
389     }
390     public void onLatestTransactionsClicked(View view) {
391         drawer.closeDrawers();
392
393         showTransactionsFragment((String) null);
394     }
395     private void resetFragmentBackStack() {
396 //        fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
397     }
398     private void showTransactionsFragment(String accName) {
399         TransactionListFragment.accountFilter.set(accName);
400         TransactionListFragment.accountFilter.notifyObservers();
401         mViewPager.setCurrentItem(1, true);
402     }
403     private void showTransactionsFragment(LedgerAccount account) {
404         showTransactionsFragment((account == null) ? (String) null : account.getName());
405 //        FragmentTransaction ft = fragmentManager.beginTransaction();
406 //        if (transactionListFragment == null) {
407 //            Log.d("flow", "MainActivity creating TransactionListFragment");
408 //            transactionListFragment = new TransactionListFragment();
409 //        }
410 //        Bundle bundle = new Bundle();
411 //        if (account != null) {
412 //            bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
413 //                    account.getName());
414 //        }
415 //        transactionListFragment.setArguments(bundle);
416 //        ft.replace(R.id.root_frame, transactionListFragment);
417 //        if (account != null)
418 //            ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
419 //        ft.commit();
420 //
421 //        currentFragment = transactionListFragment;
422     }
423     public void showAccountTransactions(LedgerAccount account) {
424         showTransactionsFragment(account);
425     }
426     @Override
427     public void onBackPressed() {
428         DrawerLayout drawer = findViewById(R.id.drawer_layout);
429         if (drawer.isDrawerOpen(GravityCompat.START)) {
430             drawer.closeDrawer(GravityCompat.START);
431         }
432         else {
433             Log.d("fragments",
434                     String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
435
436             super.onBackPressed();
437         }
438     }
439     public void updateLastUpdateTextFromDB() {
440         {
441             final MobileLedgerProfile profile = Data.profile.get();
442             long last_update =
443                     (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
444
445             Log.d("transactions", String.format("Last update = %d", last_update));
446             if (last_update == 0) {
447                 Data.lastUpdateDate.set(null);
448             }
449             else {
450                 Data.lastUpdateDate.set(new Date(last_update));
451             }
452         }
453     }
454     public void scheduleTransactionListRetrieval() {
455         if (Data.profile.get() == null) return;
456
457         retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
458
459         retrieveTransactionsTask.execute();
460     }
461     public void onStopTransactionRefreshClick(View view) {
462         Log.d("interactive", "Cancelling transactions refresh");
463         if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
464         bTransactionListCancelDownload.setEnabled(false);
465     }
466     public void onRetrieveDone(String error) {
467         progressLayout.setVisibility(View.GONE);
468
469         if (error == null) {
470             updateLastUpdateTextFromDB();
471
472             new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
473             TransactionListViewModel.scheduleTransactionListReload();
474         }
475         else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
476     }
477     public void onRetrieveStart() {
478         bTransactionListCancelDownload.setEnabled(true);
479         progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
480         progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
481         progressBar.setIndeterminate(true);
482         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
483         else progressBar.setProgress(0);
484         progressLayout.setVisibility(View.VISIBLE);
485     }
486     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
487         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
488             (progress.getTotal() == 0))
489         {
490             progressBar.setIndeterminate(true);
491         }
492         else {
493             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
494                 progressBar.setMin(0);
495             }
496             progressBar.setMax(progress.getTotal());
497             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
498                 progressBar.setProgress(progress.getProgress(), true);
499             }
500             else progressBar.setProgress(progress.getProgress());
501             progressBar.setIndeterminate(false);
502         }
503     }
504     public void fabShouldShow() {
505         MobileLedgerProfile profile = Data.profile.get();
506         if ((profile != null) && profile.isPostingPermitted()) fab.show();
507     }
508     public void navProfilesHeadClicked(View view) {
509         if (profileListExpanded) {
510             collapseProfileList();
511         }
512         else {
513             expandProfileList();
514         }
515     }
516     private void expandProfileList() {
517         profileListExpanded = true;
518
519
520         profileListContainer.setVisibility(View.VISIBLE);
521         profileListContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_down));
522         profileListHeadArrow.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180));
523         profileListHeadMore.setVisibility(View.VISIBLE);
524         profileListHeadMore.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
525         findViewById(R.id.nav_profile_list).setMinimumHeight(
526                 (int) (getResources().getDimension(R.dimen.thumb_row_height) *
527                        Data.profiles.size()));
528     }
529     private void collapseProfileList() {
530         profileListExpanded = false;
531
532         final Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up);
533         animation.setAnimationListener(new Animation.AnimationListener() {
534             @Override
535             public void onAnimationStart(Animation animation) {
536
537             }
538             @Override
539             public void onAnimationEnd(Animation animation) {
540                 profileListContainer.setVisibility(View.GONE);
541             }
542             @Override
543             public void onAnimationRepeat(Animation animation) {
544
545             }
546         });
547         mProfileListAdapter.stopEditingProfiles();
548
549         profileListContainer.startAnimation(animation);
550         profileListHeadArrow.setRotation(0f);
551         profileListHeadArrow
552                 .startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180_back));
553         profileListHeadMore.setVisibility(View.GONE);
554     }
555     public void onProfileRowClicked(View v) {
556         Data.setCurrentProfile((MobileLedgerProfile) v.getTag());
557     }
558     public void enableProfileModifications() {
559         profileModificationEnabled = true;
560         ViewGroup profileList = findViewById(R.id.nav_profile_list);
561         for (int i = 0; i < profileList.getChildCount(); i++) {
562             View aRow = profileList.getChildAt(i);
563             aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.VISIBLE);
564             aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.VISIBLE);
565         }
566         // FIXME enable rearranging
567
568     }
569     public void disableProfileModifications() {
570         profileModificationEnabled = false;
571         ViewGroup profileList = findViewById(R.id.nav_profile_list);
572         for (int i = 0; i < profileList.getChildCount(); i++) {
573             View aRow = profileList.getChildAt(i);
574             aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.GONE);
575             aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.INVISIBLE);
576         }
577         // FIXME disable rearranging
578
579     }
580     public void onAccountSummaryRowViewClicked(View view) {
581         ViewGroup row = (ViewGroup) view.getParent();
582         LedgerAccount acc = (LedgerAccount) row.getTag();
583         switch (view.getId()) {
584             case R.id.account_row_acc_name:
585             case R.id.account_expander_container:
586                 Log.d("accounts", "Account expander clicked");
587                 if (!acc.hasSubAccounts()) return;
588
589                 boolean wasExpanded = acc.isExpanded();
590
591                 View arrow = row.findViewById(R.id.account_expander_container);
592
593                 arrow.clearAnimation();
594                 ViewPropertyAnimator animator = arrow.animate();
595
596                 acc.toggleExpanded();
597                 DbOpQueue.add("update accounts set expanded=? where name=? and profile=?",
598                         new Object[]{acc.isExpanded(), acc.getName(), Data.profile.get().getUuid()
599                         });
600
601                 if (wasExpanded) {
602                     Log.d("accounts", String.format("Collapsing account '%s'", acc.getName()));
603                     arrow.setRotation(0);
604                     animator.rotationBy(180);
605
606                     // removing all child accounts from the view
607                     int start = -1, count = 0;
608                     try (LockHolder lh = Data.accounts.lockForWriting()) {
609                         for (int i = 0; i < Data.accounts.size(); i++) {
610                             if (acc.isParentOf(Data.accounts.get(i))) {
611 //                                Log.d("accounts", String.format("Found a child '%s' at position %d",
612 //                                        Data.accounts.get(i).getName(), i));
613                                 if (start == -1) {
614                                     start = i;
615                                 }
616                                 count++;
617                             }
618                             else {
619                                 if (start != -1) {
620 //                                    Log.d("accounts",
621 //                                            String.format("Found a non-child '%s' at position %d",
622 //                                                    Data.accounts.get(i).getName(), i));
623                                     break;
624                                 }
625                             }
626                         }
627
628                         if (start != -1) {
629                             for (int j = 0; j < count; j++) {
630 //                                Log.d("accounts", String.format("Removing item %d: %s", start + j,
631 //                                        Data.accounts.get(start).getName()));
632                                 Data.accounts.removeQuietly(start);
633                             }
634
635                             mAccountSummaryFragment.modelAdapter
636                                     .notifyItemRangeRemoved(start, count);
637                         }
638                     }
639                 }
640                 else {
641                     Log.d("accounts", String.format("Expanding account '%s'", acc.getName()));
642                     arrow.setRotation(180);
643                     animator.rotationBy(-180);
644                     List<LedgerAccount> children =
645                             Data.profile.get().loadVisibleChildAccountsOf(acc);
646                     try (LockHolder lh = Data.accounts.lockForWriting()) {
647                         int parentPos = Data.accounts.indexOf(acc);
648                         if (parentPos != -1) {
649                             // may have disappeared in a concurrent refresh operation
650                             Data.accounts.addAllQuietly(parentPos + 1, children);
651                             mAccountSummaryFragment.modelAdapter
652                                     .notifyItemRangeInserted(parentPos + 1, children.size());
653                         }
654                     }
655                 }
656                 break;
657             case R.id.account_row_acc_amounts:
658                 if (acc.getAmountCount() > AccountSummaryAdapter.AMOUNT_LIMIT) {
659                     acc.toggleAmountsExpanded();
660                     DbOpQueue
661                             .add("update accounts set amounts_expanded=? where name=? and profile=?",
662                                     new Object[]{acc.amountsExpanded(), acc.getName(),
663                                                  Data.profile.get().getUuid()
664                                     });
665                     Data.accounts.triggerItemChangedNotification(acc);
666                 }
667                 break;
668         }
669     }
670
671     public class SectionsPagerAdapter extends FragmentPagerAdapter {
672
673         public SectionsPagerAdapter(FragmentManager fm) {
674             super(fm);
675         }
676
677         @Override
678         public Fragment getItem(int position) {
679             Log.d("main", String.format("Switching to fragment %d", position));
680             switch (position) {
681                 case 0:
682 //                    Log.d("flow", "Creating account summary fragment");
683                     return mAccountSummaryFragment = new AccountSummaryFragment();
684                 case 1:
685                     return new TransactionListFragment();
686                 default:
687                     throw new IllegalStateException(
688                             String.format("Unexpected fragment index: " + "%d", position));
689             }
690         }
691
692         @Override
693         public int getCount() {
694             return 2;
695         }
696     }
697 }