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.
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.
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/>.
18 package net.ktnx.mobileledger.ui.activity;
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;
41 import com.google.android.material.floatingactionbutton.FloatingActionButton;
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;
62 import org.jetbrains.annotations.NotNull;
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;
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;
81 import static net.ktnx.mobileledger.utils.Logger.debug;
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;
90 private View profileListHeadMore, profileListHeadCancel, profileListHeadAddProfile;
91 private View bTransactionListCancelDownload;
92 private SectionsPagerAdapter mSectionsPagerAdapter;
93 private ViewPager mViewPager;
94 private FloatingActionButton fab;
95 private ProfilesRecyclerViewAdapter mProfileListAdapter;
96 private int mCurrentPage;
97 private String mAccountFilter;
98 private boolean mBackMeansToAccountList = false;
99 private Toolbar mToolbar;
100 private DrawerLayout.SimpleDrawerListener drawerListener;
101 private ActionBarDrawerToggle barDrawerToggle;
102 private ViewPager.SimpleOnPageChangeListener pageChangeListener;
103 private MobileLedgerProfile profile;
105 protected void onStart() {
108 debug("flow", String.format(Locale.ENGLISH,
109 "MainActivity.onStart(), currentPage is %d, accountFilter is %s", mCurrentPage,
110 (mAccountFilter == null) ? "<NULL>" : mAccountFilter));
111 mViewPager.setCurrentItem(mCurrentPage, false);
112 if (mAccountFilter != null) showTransactionsFragment(mAccountFilter);
113 else Data.accountFilter.setValue(null);
117 protected void onSaveInstanceState(@NotNull Bundle outState) {
118 super.onSaveInstanceState(outState);
119 outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
120 if (mAccountFilter != null) outState.putString(STATE_ACC_FILTER, mAccountFilter);
123 protected void onDestroy() {
124 mSectionsPagerAdapter = null;
125 RecyclerView root = findViewById(R.id.nav_profile_list);
126 if (root != null) root.setAdapter(null);
127 if (drawer != null) drawer.removeDrawerListener(drawerListener);
128 drawerListener = null;
129 if (drawer != null) drawer.removeDrawerListener(barDrawerToggle);
130 barDrawerToggle = null;
131 if (mViewPager != null) mViewPager.removeOnPageChangeListener(pageChangeListener);
132 pageChangeListener = null;
136 protected void setupProfileColors() {
137 SharedPreferences prefs = getPreferences(MODE_PRIVATE);
138 int profileColor = prefs.getInt(PREF_THEME_ID, -2);
139 if (profileColor == -2) profileColor = Data.retrieveCurrentThemeIdFromDb();
140 Colors.setupTheme(this, profileColor);
141 Colors.profileThemeId = profileColor;
142 storeThemeIdInPrefs(profileColor);
145 protected void onResume() {
150 protected void onCreate(Bundle savedInstanceState) {
151 super.onCreate(savedInstanceState);
152 debug("flow", "MainActivity.onCreate()");
153 setContentView(R.layout.activity_main);
155 fab = findViewById(R.id.btn_add_transaction);
156 profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
157 profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
158 LinearLayout profileListHeadMoreAndCancel =
159 findViewById(R.id.nav_profile_list_head_buttons);
160 profileListHeadAddProfile = findViewById(R.id.nav_new_profile_button);
161 drawer = findViewById(R.id.drawer_layout);
162 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
163 mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
164 mViewPager = findViewById(R.id.root_frame);
166 Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
167 if (extra != null && savedInstanceState == null) savedInstanceState = extra;
170 mToolbar = findViewById(R.id.toolbar);
171 setSupportActionBar(mToolbar);
173 Data.profile.observe(this, this::onProfileChanged);
175 Data.profiles.observe(this, this::onProfileListChanged);
177 if (barDrawerToggle == null) {
178 barDrawerToggle = new ActionBarDrawerToggle(this, drawer, mToolbar,
179 R.string.navigation_drawer_open, R.string.navigation_drawer_close);
180 drawer.addDrawerListener(barDrawerToggle);
182 barDrawerToggle.syncState();
184 TextView ver = drawer.findViewById(R.id.drawer_version_text);
188 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
189 ver.setText(pi.versionName);
191 catch (Exception e) {
195 markDrawerItemCurrent(R.id.nav_account_summary);
197 mViewPager.setAdapter(mSectionsPagerAdapter);
199 if (pageChangeListener == null) {
200 pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
202 public void onPageSelected(int position) {
203 mCurrentPage = position;
206 markDrawerItemCurrent(R.id.nav_account_summary);
209 markDrawerItemCurrent(R.id.nav_latest_transactions);
212 Log.e("MainActivity",
213 String.format("Unexpected page index %d", position));
216 super.onPageSelected(position);
219 mViewPager.addOnPageChangeListener(pageChangeListener);
223 if (savedInstanceState != null) {
224 int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
225 if (currentPage != -1) {
226 mCurrentPage = currentPage;
228 mAccountFilter = savedInstanceState.getString(STATE_ACC_FILTER, null);
230 else mAccountFilter = null;
232 Data.lastUpdateDate.observe(this, this::updateLastUpdateDisplay);
234 findViewById(R.id.btn_no_profiles_add)
235 .setOnClickListener(v -> startEditProfileActivity(null));
237 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
239 findViewById(R.id.nav_new_profile_button)
240 .setOnClickListener(v -> startEditProfileActivity(null));
242 RecyclerView root = findViewById(R.id.nav_profile_list);
244 throw new RuntimeException("Can't get hold on the transaction value view");
246 if (mProfileListAdapter == null) mProfileListAdapter = new ProfilesRecyclerViewAdapter();
247 root.setAdapter(mProfileListAdapter);
249 mProfileListAdapter.editingProfiles.observe(this, newValue -> {
251 profileListHeadMore.setVisibility(View.GONE);
252 profileListHeadCancel.setVisibility(View.VISIBLE);
253 profileListHeadAddProfile.setVisibility(View.VISIBLE);
254 if (drawer.isDrawerOpen(GravityCompat.START)) {
255 profileListHeadMore.startAnimation(
256 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
257 profileListHeadCancel.startAnimation(
258 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
259 profileListHeadAddProfile.startAnimation(
260 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
264 profileListHeadCancel.setVisibility(View.GONE);
265 profileListHeadMore.setVisibility(View.VISIBLE);
266 profileListHeadAddProfile.setVisibility(View.GONE);
267 if (drawer.isDrawerOpen(GravityCompat.START)) {
268 profileListHeadCancel.startAnimation(
269 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
270 profileListHeadMore.startAnimation(
271 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
272 profileListHeadAddProfile.startAnimation(
273 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
277 mProfileListAdapter.notifyDataSetChanged();
280 LinearLayoutManager llm = new LinearLayoutManager(this);
282 llm.setOrientation(RecyclerView.VERTICAL);
283 root.setLayoutManager(llm);
285 profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
286 profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
287 profileListHeadMoreAndCancel
288 .setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
289 if (drawerListener == null) {
290 drawerListener = new DrawerLayout.SimpleDrawerListener() {
292 public void onDrawerClosed(View drawerView) {
293 super.onDrawerClosed(drawerView);
294 mProfileListAdapter.setAnimationsEnabled(false);
295 mProfileListAdapter.editingProfiles.setValue(false);
298 public void onDrawerOpened(View drawerView) {
299 super.onDrawerOpened(drawerView);
300 mProfileListAdapter.setAnimationsEnabled(true);
303 drawer.addDrawerListener(drawerListener);
307 private void scheduleDataRetrievalIfStale(Date lastUpdate) {
308 long now = new Date().getTime();
309 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
310 if (lastUpdate == null) debug("db::", "WEB data never fetched. scheduling a fetch");
311 else debug("db", String.format(Locale.ENGLISH,
312 "WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
313 lastUpdate.getTime() / 1000f, now / 1000f));
315 Data.scheduleTransactionListRetrieval(this);
318 private void createShortcuts(List<MobileLedgerProfile> list) {
319 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return;
321 List<ShortcutInfo> shortcuts = new ArrayList<>();
323 for (MobileLedgerProfile p : list) {
324 if (!p.isPostingPermitted()) continue;
326 ShortcutInfo si = new ShortcutInfo.Builder(this, "new_transaction_" + p.getUuid())
327 .setShortLabel(p.getName())
328 .setIcon(Icon.createWithResource(this, R.drawable.svg_thick_plus_white))
330 new Intent(Intent.ACTION_VIEW, null, this, NewTransactionActivity.class)
331 .putExtra("profile_uuid", p.getUuid())).setRank(i).build();
335 ShortcutManager sm = getSystemService(ShortcutManager.class);
336 sm.setDynamicShortcuts(shortcuts);
338 private void onProfileListChanged(List<MobileLedgerProfile> newList) {
339 if (newList == null) {
340 // profiles not yet loaded from DB
341 findViewById(R.id.loading_layout).setVisibility(View.VISIBLE);
342 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
343 findViewById(R.id.pager_layout).setVisibility(View.GONE);
347 if (newList.isEmpty()) {
348 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
349 findViewById(R.id.pager_layout).setVisibility(View.GONE);
350 findViewById(R.id.loading_layout).setVisibility(View.GONE);
354 findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
355 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
356 findViewById(R.id.loading_layout).setVisibility(View.GONE);
358 findViewById(R.id.nav_profile_list).setMinimumHeight(
359 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
361 debug("profiles", "profile list changed");
362 mProfileListAdapter.notifyDataSetChanged();
364 createShortcuts(newList);
367 * called when the current profile has changed
369 private void onProfileChanged(MobileLedgerProfile profile) {
370 boolean haveProfile = profile != null;
371 findViewById(R.id.no_profiles_layout).setVisibility(haveProfile ? View.GONE : View.VISIBLE);
372 findViewById(R.id.pager_layout).setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
374 if (haveProfile) setTitle(profile.getName());
375 else setTitle(R.string.app_name);
377 this.profile = profile;
379 mProfileListAdapter.notifyDataSetChanged();
381 int newProfileTheme = haveProfile ? profile.getThemeId() : -1;
382 if (newProfileTheme != Colors.profileThemeId) {
384 String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
386 MainActivity.this.profileThemeChanged();
387 Colors.profileThemeId = newProfileTheme;
388 // profileThemeChanged would restart the activity, so no need to reload the
393 drawer.closeDrawers();
395 Data.transactions.clear();
396 debug("transactions", "requesting list reload");
397 TransactionListViewModel.scheduleTransactionListReload();
399 Data.accounts.clear();
400 AccountSummaryViewModel.scheduleAccountListReload();
403 if (profile.isPostingPermitted()) {
404 mToolbar.setSubtitle(null);
408 mToolbar.setSubtitle(R.string.profile_subitlte_read_only);
413 mToolbar.setSubtitle(null);
417 updateLastUpdateTextFromDB();
419 private void updateLastUpdateDisplay(Date newValue) {
420 LinearLayout l = findViewById(R.id.transactions_last_update_layout);
421 TextView v = findViewById(R.id.transactions_last_update);
422 if (newValue == null) {
423 l.setVisibility(View.INVISIBLE);
424 debug("main", "no last update date :(");
427 final String text = DateFormat.getDateTimeInstance().format(newValue);
429 l.setVisibility(View.VISIBLE);
430 debug("main", String.format("Date formatted: %s", text));
433 scheduleDataRetrievalIfStale(newValue);
435 private void profileThemeChanged() {
436 Bundle bundle = new Bundle();
437 onSaveInstanceState(bundle);
439 storeThemeIdInPrefs(profile.getThemeId());
441 // restart activity to reflect theme change
444 // un-hook all observed LiveData
445 Data.profile.removeObservers(this);
446 Data.profiles.removeObservers(this);
447 Data.lastUpdateDate.removeObservers(this);
448 Intent intent = new Intent(this, this.getClass());
449 intent.putExtra(BUNDLE_SAVED_STATE, bundle);
450 startActivity(intent);
452 private void storeThemeIdInPrefs(int themeId) {
453 // store the new theme id in the preferences
454 SharedPreferences prefs = getPreferences(MODE_PRIVATE);
455 SharedPreferences.Editor e = prefs.edit();
456 e.putInt(PREF_THEME_ID, themeId);
459 public void startEditProfileActivity(MobileLedgerProfile profile) {
460 Intent intent = new Intent(this, ProfileDetailActivity.class);
461 Bundle args = new Bundle();
462 if (profile != null) {
463 int index = Data.getProfileIndex(profile);
464 if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
466 intent.putExtras(args);
467 startActivity(intent, args);
469 private void setupProfile() {
470 MLDB.getOption(MLDB.OPT_PROFILE_UUID, null, new GetOptCallback() {
472 protected void onResult(String profileUUID) {
473 MobileLedgerProfile startupProfile;
475 startupProfile = Data.getProfile(profileUUID);
476 Data.setCurrentProfile(startupProfile);
480 public void fabNewTransactionClicked(View view) {
481 Intent intent = new Intent(this, NewTransactionActivity.class);
482 startActivity(intent);
483 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
485 public void navSettingsClicked(View view) {
486 Intent intent = new Intent(this, SettingsActivity.class);
487 startActivity(intent);
488 drawer.closeDrawers();
490 public void markDrawerItemCurrent(int id) {
491 TextView item = drawer.findViewById(id);
492 item.setBackgroundColor(Colors.tableRowDarkBG);
494 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
495 for (int i = 0; i < actions.getChildCount(); i++) {
496 View view = actions.getChildAt(i);
497 if (view.getId() != id) {
498 view.setBackgroundColor(Color.TRANSPARENT);
502 public void onAccountSummaryClicked(View view) {
503 drawer.closeDrawers();
505 showAccountSummaryFragment();
507 private void showAccountSummaryFragment() {
508 mViewPager.setCurrentItem(0, true);
509 Data.accountFilter.setValue(null);
511 public void onLatestTransactionsClicked(View view) {
512 drawer.closeDrawers();
514 showTransactionsFragment((String) null);
516 private void showTransactionsFragment(String accName) {
517 Data.accountFilter.setValue(accName);
518 mViewPager.setCurrentItem(1, true);
520 private void showTransactionsFragment(LedgerAccount account) {
521 showTransactionsFragment((account == null) ? null : account.getName());
523 public void showAccountTransactions(LedgerAccount account) {
524 mBackMeansToAccountList = true;
525 showTransactionsFragment(account);
528 public void onBackPressed() {
529 DrawerLayout drawer = findViewById(R.id.drawer_layout);
530 if (drawer.isDrawerOpen(GravityCompat.START)) {
531 drawer.closeDrawer(GravityCompat.START);
534 if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
535 Data.accountFilter.setValue(null);
536 showAccountSummaryFragment();
537 mBackMeansToAccountList = false;
540 debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
541 getSupportFragmentManager().getBackStackEntryCount()));
543 super.onBackPressed();
547 public void updateLastUpdateTextFromDB() {
548 if (profile == null) return;
550 long last_update = profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
552 debug("transactions", String.format(Locale.ENGLISH, "Last update = %d", last_update));
553 if (last_update == 0) {
554 Data.lastUpdateDate.postValue(null);
557 Data.lastUpdateDate.postValue(new Date(last_update));
560 public void onStopTransactionRefreshClick(View view) {
561 debug("interactive", "Cancelling transactions refresh");
562 Data.stopTransactionsRetrieval();
563 bTransactionListCancelDownload.setEnabled(false);
565 public void onRetrieveDone(String error) {
566 Data.transactionRetrievalDone();
567 findViewById(R.id.transaction_progress_layout).setVisibility(View.GONE);
570 updateLastUpdateTextFromDB();
572 new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
573 TransactionListViewModel.scheduleTransactionListReload();
575 else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
577 public void onRetrieveStart() {
578 ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
579 bTransactionListCancelDownload.setEnabled(true);
580 ColorStateList csl = Colors.getColorStateList();
581 progressBar.setIndeterminateTintList(csl);
582 progressBar.setProgressTintList(csl);
583 progressBar.setIndeterminate(true);
584 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
585 else progressBar.setProgress(0);
586 findViewById(R.id.transaction_progress_layout).setVisibility(View.VISIBLE);
588 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
589 ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
590 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
591 (progress.getTotal() == 0))
593 progressBar.setIndeterminate(true);
596 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
597 progressBar.setMin(0);
599 progressBar.setMax(progress.getTotal());
600 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
601 progressBar.setProgress(progress.getProgress(), true);
603 else progressBar.setProgress(progress.getProgress());
604 progressBar.setIndeterminate(false);
607 public void fabShouldShow() {
608 if ((profile != null) && profile.isPostingPermitted()) fab.show();
610 public void fabHide() {
613 public void onAccountSummaryRowViewClicked(View view) {
615 if (view.getId() == R.id.account_expander) row = (ViewGroup) view.getParent().getParent();
616 else row = (ViewGroup) view.getParent();
618 LedgerAccount acc = (LedgerAccount) row.getTag();
619 switch (view.getId()) {
620 case R.id.account_row_acc_name:
621 case R.id.account_expander:
622 case R.id.account_expander_container:
623 debug("accounts", "Account expander clicked");
624 if (!acc.hasSubAccounts()) return;
626 boolean wasExpanded = acc.isExpanded();
628 View arrow = row.findViewById(R.id.account_expander_container);
630 arrow.clearAnimation();
631 ViewPropertyAnimator animator = arrow.animate();
633 acc.toggleExpanded();
634 DbOpQueue.add("update accounts set expanded=? where name=? and profile=?",
635 new Object[]{acc.isExpanded(), acc.getName(), profile.getUuid()
639 debug("accounts", String.format("Collapsing account '%s'", acc.getName()));
640 arrow.setRotation(0);
641 animator.rotationBy(180);
643 // removing all child accounts from the view
644 int start = -1, count = 0;
645 try (LockHolder ignored = Data.accounts.lockForWriting()) {
646 for (int i = 0; i < Data.accounts.size(); i++) {
647 if (acc.isParentOf(Data.accounts.get(i))) {
648 // debug("accounts", String.format("Found a child '%s' at position %d",
649 // Data.accounts.get(i).getName(), i));
658 // String.format("Found a non-child '%s' at position %d",
659 // Data.accounts.get(i).getName(), i));
666 for (int j = 0; j < count; j++) {
667 // debug("accounts", String.format("Removing item %d: %s", start + j,
668 // Data.accounts.get(start).getName()));
669 Data.accounts.removeQuietly(start);
672 mAccountSummaryFragment.modelAdapter
673 .notifyItemRangeRemoved(start, count);
678 debug("accounts", String.format("Expanding account '%s'", acc.getName()));
679 arrow.setRotation(180);
680 animator.rotationBy(-180);
681 List<LedgerAccount> children = profile.loadVisibleChildAccountsOf(acc);
682 try (LockHolder ignored = Data.accounts.lockForWriting()) {
683 int parentPos = Data.accounts.indexOf(acc);
684 if (parentPos != -1) {
685 // may have disappeared in a concurrent refresh operation
686 Data.accounts.addAllQuietly(parentPos + 1, children);
687 mAccountSummaryFragment.modelAdapter
688 .notifyItemRangeInserted(parentPos + 1, children.size());
693 case R.id.account_row_acc_amounts:
694 if (acc.getAmountCount() > AccountSummaryAdapter.AMOUNT_LIMIT) {
695 acc.toggleAmountsExpanded();
697 .add("update accounts set amounts_expanded=? where name=? and profile=?",
698 new Object[]{acc.amountsExpanded(), acc.getName(),
701 Data.accounts.triggerItemChangedNotification(acc);
707 public class SectionsPagerAdapter extends FragmentPagerAdapter {
709 SectionsPagerAdapter(FragmentManager fm) {
715 public Fragment getItem(int position) {
716 debug("main", String.format(Locale.ENGLISH, "Switching to fragment %d", position));
719 // debug("flow", "Creating account summary fragment");
720 return mAccountSummaryFragment = new AccountSummaryFragment();
722 return new TransactionListFragment();
724 throw new IllegalStateException(
725 String.format("Unexpected fragment index: " + "%d", position));
730 public int getCount() {