]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/account_summary/AccountSummaryFragment.java
observe background task count in the UI fragments
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / account_summary / AccountSummaryFragment.java
1 /*
2  * Copyright © 2019 Damyan Ivanov.
3  * This file is part of Mobile-Ledger.
4  * Mobile-Ledger 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  * Mobile-Ledger 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 Mobile-Ledger. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.ui.account_summary;
19
20 import android.arch.lifecycle.ViewModelProviders;
21 import android.content.Context;
22 import android.content.SharedPreferences;
23 import android.os.Bundle;
24 import android.preference.PreferenceManager;
25 import android.support.annotation.NonNull;
26 import android.support.annotation.Nullable;
27 import android.support.design.widget.FloatingActionButton;
28 import android.support.v7.widget.LinearLayoutManager;
29 import android.support.v7.widget.RecyclerView;
30 import android.util.Log;
31 import android.view.LayoutInflater;
32 import android.view.Menu;
33 import android.view.MenuInflater;
34 import android.view.MenuItem;
35 import android.view.View;
36 import android.view.ViewGroup;
37
38 import net.ktnx.mobileledger.R;
39 import net.ktnx.mobileledger.async.RetrieveAccountsTask;
40 import net.ktnx.mobileledger.model.Data;
41 import net.ktnx.mobileledger.model.LedgerAccount;
42 import net.ktnx.mobileledger.ui.MobileLedgerListFragment;
43 import net.ktnx.mobileledger.ui.RecyclerItemListener;
44 import net.ktnx.mobileledger.ui.activity.MainActivity;
45 import net.ktnx.mobileledger.utils.MLDB;
46
47 import java.lang.ref.WeakReference;
48 import java.util.Date;
49 import java.util.List;
50 import java.util.Observable;
51 import java.util.Observer;
52
53 import static net.ktnx.mobileledger.ui.activity.SettingsActivity.PREF_KEY_SHOW_ONLY_STARRED_ACCOUNTS;
54
55 public class AccountSummaryFragment extends MobileLedgerListFragment {
56
57     private static long account_list_last_updated;
58     private static boolean account_list_needs_update = true;
59     MenuItem mShowHiddenAccounts;
60     SharedPreferences.OnSharedPreferenceChangeListener sBindPreferenceSummaryToValueListener;
61     private AccountSummaryViewModel model;
62     private AccountSummaryAdapter modelAdapter;
63     private Menu optMenu;
64     private FloatingActionButton fab;
65     private Observer backgroundTaskCountObserver;
66     @Override
67     public void onDestroy() {
68         if(backgroundTaskCountObserver!= null) {
69             Log.d("acc", "destroying background task count observer");
70             Data.backgroundTaskCount.deleteObserver(backgroundTaskCountObserver);
71         }
72         super.onDestroy();
73     }
74     @Override
75     public void onCreate(@Nullable Bundle savedInstanceState) {
76         super.onCreate(savedInstanceState);
77         setHasOptionsMenu(true);
78
79         if (backgroundTaskCountObserver == null) {
80             Log.d("acc", "creating background task count observer");
81             Data.backgroundTaskCount.addObserver(backgroundTaskCountObserver = new Observer() {
82                 @Override
83                 public void update(Observable o, Object arg) {
84                     if (mActivity == null) return;
85                     if (swiper == null) return;
86                     mActivity.runOnUiThread(new Runnable() {
87                         @Override
88                         public void run() {
89                             int cnt = Data.backgroundTaskCount.get();
90                             Log.d("acc", String.format("background task count changed to %d", cnt));
91                             swiper.setRefreshing(cnt > 0);
92                         }
93                     });
94                 }
95             });
96         }
97     }
98     public void onAttach(Context context) {
99         super.onAttach(context);
100         mActivity = (MainActivity) context;
101     }
102     @Override
103     public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
104                              @Nullable Bundle savedInstanceState) {
105         return inflater.inflate(R.layout.account_summary_fragment, container, false);
106     }
107
108     @Override
109     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
110         super.onActivityCreated(savedInstanceState);
111
112         mActivity.markDrawerItemCurrent(R.id.nav_account_summary);
113
114         model = ViewModelProviders.of(this).get(AccountSummaryViewModel.class);
115         List<LedgerAccount> accounts = model.getAccounts(this.getContext());
116         modelAdapter = new AccountSummaryAdapter(accounts);
117
118         RecyclerView root = mActivity.findViewById(R.id.account_root);
119         root.setAdapter(modelAdapter);
120
121         LinearLayoutManager llm = new LinearLayoutManager(mActivity);
122         llm.setOrientation(LinearLayoutManager.VERTICAL);
123         root.setLayoutManager(llm);
124
125         fab = mActivity.findViewById(R.id.btn_add_transaction);
126
127         root.addOnItemTouchListener(new RecyclerItemListener(mActivity, root,
128                 new RecyclerItemListener.RecyclerTouchListener() {
129                     @Override
130                     public void onClickItem(View v, int position) {
131                         Log.d("value", String.format("item %d clicked", position));
132                         if (modelAdapter.isSelectionActive()) {
133                             modelAdapter.selectItem(position);
134                         }
135                         else {
136                             List<LedgerAccount> accounts = model.getAccounts(mActivity);
137                             if (accounts != null) {
138                                 LedgerAccount account = accounts.get(position);
139
140                                 mActivity.showAccountTransactions(account);
141                             }
142                         }
143                     }
144
145                     @Override
146                     public void onLongClickItem(View v, int position) {
147                         Log.d("value", String.format("item %d long-clicked", position));
148                         modelAdapter.startSelection();
149                         if (optMenu != null) {
150                             optMenu.findItem(R.id.menu_acc_summary_cancel_selection)
151                                     .setVisible(true);
152                             optMenu.findItem(R.id.menu_acc_summary_confirm_selection)
153                                     .setVisible(true);
154                             optMenu.findItem(R.id.menu_acc_summary_only_starred).setVisible(false);
155                         }
156                         {
157                             if (fab != null) fab.hide();
158                         }
159                     }
160                 }));
161
162         fab.show();
163         root.addOnScrollListener(new RecyclerView.OnScrollListener() {
164             @Override
165             public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
166                 if (fab != null) {
167                     if (dy < 0) fab.show();
168                     if (dy > 0) fab.hide();
169                 }
170             }
171         });
172         swiper = mActivity.findViewById(R.id.account_swiper);
173         swiper.setColorSchemeResources(R.color.colorPrimary, R.color.colorAccent);
174         swiper.setOnRefreshListener(() -> {
175             Log.d("ui", "refreshing accounts via swipe");
176             update_accounts(true);
177         });
178
179         Data.accounts.addObserver(new Observer() {
180             @Override
181             public void update(Observable o, Object arg) {
182                 mActivity.runOnUiThread(new Runnable() {
183                     @Override
184                     public void run() {
185                         modelAdapter.notifyDataSetChanged();
186                     }
187                 });
188             }
189         });
190         update_account_table();
191     }
192
193     private void update_accounts(boolean force) {
194         long now = new Date().getTime();
195         if ((now > (account_list_last_updated + (24 * 3600 * 1000))) || force) {
196             Log.d("db",
197                     "accounts last updated at " + account_list_last_updated + " and now is " + now +
198                     ". re-fetching");
199             update_accounts();
200         }
201     }
202
203     private void update_accounts() {
204         RetrieveAccountsTask task = new RetrieveAccountsTask(new WeakReference<>(mActivity));
205
206         task.setPref(PreferenceManager.getDefaultSharedPreferences(mActivity));
207         task.execute();
208
209     }
210     private void update_account_table() {
211         if (this.getContext() == null) return;
212
213         model.reloadAccounts(this.getContext());
214         modelAdapter.notifyDataSetChanged();
215     }
216     public void onShowOnlyStarredClicked(MenuItem mi) {
217         SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mActivity);
218         boolean flag = pref.getBoolean(PREF_KEY_SHOW_ONLY_STARRED_ACCOUNTS, false);
219
220         SharedPreferences.Editor editor = pref.edit();
221         editor.putBoolean(PREF_KEY_SHOW_ONLY_STARRED_ACCOUNTS, !flag);
222         Log.d("pref", "Setting show only starred accounts pref to " + (flag ? "false" : "true"));
223         editor.apply();
224
225         update_account_table();
226     }
227
228     void stopSelection() {
229         modelAdapter.stopSelection();
230         if (optMenu != null) {
231             optMenu.findItem(R.id.menu_acc_summary_cancel_selection).setVisible(false);
232             optMenu.findItem(R.id.menu_acc_summary_confirm_selection).setVisible(false);
233             optMenu.findItem(R.id.menu_acc_summary_only_starred).setVisible(true);
234         }
235         {
236             if (fab != null) fab.show();
237         }
238     }
239     public void onCancelAccSelection(MenuItem item) {
240         stopSelection();
241     }
242     public void onConfirmAccSelection(MenuItem item) {
243         model.commitSelections(mActivity);
244         stopSelection();
245     }
246     @Override
247     public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
248         // Inflate the menu; this adds items to the action bar if it is present.
249         inflater.inflate(R.menu.account_summary, menu);
250         optMenu = menu;
251
252         mShowHiddenAccounts = menu.findItem(R.id.menu_acc_summary_only_starred);
253         if (mShowHiddenAccounts == null) throw new AssertionError();
254
255         sBindPreferenceSummaryToValueListener = (preference, value) -> mShowHiddenAccounts
256                 .setChecked(preference.getBoolean(PREF_KEY_SHOW_ONLY_STARRED_ACCOUNTS, false));
257         SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mActivity);
258         pref.registerOnSharedPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
259
260         mShowHiddenAccounts.setChecked(pref.getBoolean(PREF_KEY_SHOW_ONLY_STARRED_ACCOUNTS, false));
261
262         Log.d("menu", "MainActivity: onCreateOptionsMenu called");
263     }
264 }