]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/transaction_list/TransactionListFragment.java
avoid scrolling to the last 'go to date' after reconfiguration
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / transaction_list / TransactionListFragment.java
1 /*
2  * Copyright © 2020 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.transaction_list;
19
20 import android.content.Context;
21 import android.database.Cursor;
22 import android.os.AsyncTask;
23 import android.os.Bundle;
24 import android.view.LayoutInflater;
25 import android.view.Menu;
26 import android.view.MenuInflater;
27 import android.view.MenuItem;
28 import android.view.View;
29 import android.view.ViewGroup;
30 import android.view.inputmethod.InputMethodManager;
31 import android.widget.AutoCompleteTextView;
32
33 import androidx.annotation.NonNull;
34 import androidx.annotation.Nullable;
35 import androidx.recyclerview.widget.LinearLayoutManager;
36 import androidx.recyclerview.widget.RecyclerView;
37
38 import com.google.android.material.snackbar.Snackbar;
39
40 import net.ktnx.mobileledger.R;
41 import net.ktnx.mobileledger.async.TransactionDateFinder;
42 import net.ktnx.mobileledger.model.Data;
43 import net.ktnx.mobileledger.ui.DatePickerFragment;
44 import net.ktnx.mobileledger.ui.MobileLedgerListFragment;
45 import net.ktnx.mobileledger.ui.activity.MainActivity;
46 import net.ktnx.mobileledger.utils.Colors;
47 import net.ktnx.mobileledger.utils.Globals;
48 import net.ktnx.mobileledger.utils.Logger;
49 import net.ktnx.mobileledger.utils.MLDB;
50 import net.ktnx.mobileledger.utils.SimpleDate;
51
52 import org.jetbrains.annotations.NotNull;
53
54 import java.util.Locale;
55
56 import static android.content.Context.INPUT_METHOD_SERVICE;
57 import static net.ktnx.mobileledger.utils.Logger.debug;
58
59 // TODO: support transaction-level comment
60
61 public class TransactionListFragment extends MobileLedgerListFragment
62         implements DatePickerFragment.DatePickedListener {
63     private MenuItem menuTransactionListFilter;
64     private View vAccountFilter;
65     private AutoCompleteTextView accNameFilter;
66     @Override
67     public void onCreate(@Nullable Bundle savedInstanceState) {
68         super.onCreate(savedInstanceState);
69         setHasOptionsMenu(true);
70     }
71     @Override
72     public void onAttach(@NotNull Context context) {
73         super.onAttach(context);
74         mActivity = (MainActivity) context;
75     }
76     @Nullable
77     @Override
78     public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
79                              @Nullable Bundle savedInstanceState) {
80         return inflater.inflate(R.layout.transaction_list_fragment, container, false);
81     }
82     @Override
83     public void onResume() {
84         super.onResume();
85         debug("flow", "TransactionListFragment.onResume()");
86     }
87     @Override
88     public void onStop() {
89         super.onStop();
90         debug("flow", "TransactionListFragment.onStop()");
91     }
92     @Override
93     public void onPause() {
94         super.onPause();
95         debug("flow", "TransactionListFragment.onPause()");
96     }
97     @Override
98     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
99         debug("flow", "TransactionListFragment.onActivityCreated called");
100         super.onActivityCreated(savedInstanceState);
101
102         Data.backgroundTasksRunning.observe(getViewLifecycleOwner(),
103                 this::onBackgroundTaskRunningChanged);
104
105         swiper = mActivity.findViewById(R.id.transaction_swipe);
106         if (swiper == null)
107             throw new RuntimeException("Can't get hold on the swipe layout");
108         root = mActivity.findViewById(R.id.transaction_root);
109         if (root == null)
110             throw new RuntimeException("Can't get hold on the transaction value view");
111         modelAdapter = new TransactionListAdapter();
112         root.setAdapter(modelAdapter);
113
114         mActivity.fabShouldShow();
115
116         manageFabOnScroll();
117
118         LinearLayoutManager llm = new LinearLayoutManager(mActivity);
119
120         llm.setOrientation(RecyclerView.VERTICAL);
121         root.setLayoutManager(llm);
122
123         swiper.setOnRefreshListener(() -> {
124             debug("ui", "refreshing transactions via swipe");
125             Data.scheduleTransactionListRetrieval(mActivity);
126         });
127
128         Colors.themeWatch.observe(getViewLifecycleOwner(), this::themeChanged);
129
130         vAccountFilter = mActivity.findViewById(R.id.transaction_list_account_name_filter);
131         accNameFilter = mActivity.findViewById(R.id.transaction_filter_account_name);
132
133         MLDB.hookAutocompletionAdapter(mActivity, accNameFilter, "accounts", "name");
134         accNameFilter.setOnItemClickListener((parent, view, position, id) -> {
135 //                debug("tmp", "direct onItemClick");
136             Cursor c = (Cursor) parent.getItemAtPosition(position);
137             Data.accountFilter.setValue(c.getString(1));
138             Globals.hideSoftKeyboard(mActivity);
139         });
140
141         Data.accountFilter.observe(getViewLifecycleOwner(), this::onAccountNameFilterChanged);
142
143         TransactionListViewModel.updating.addObserver(
144                 (o, arg) -> swiper.setRefreshing(TransactionListViewModel.updating.get()));
145         TransactionListViewModel.updateError.addObserver((o, arg) -> {
146             String err = TransactionListViewModel.updateError.get();
147             if (err == null)
148                 return;
149
150             Snackbar.make(this.root, err, Snackbar.LENGTH_LONG)
151                     .show();
152             TransactionListViewModel.updateError.set(null);
153         });
154         Data.transactions.addObserver(
155                 (o, arg) -> mActivity.runOnUiThread(() -> modelAdapter.notifyDataSetChanged()));
156
157         mActivity.findViewById(R.id.clearAccountNameFilter)
158                  .setOnClickListener(v -> {
159                      Data.accountFilter.setValue(null);
160                      vAccountFilter.setVisibility(View.GONE);
161                      menuTransactionListFilter.setVisible(true);
162                      Globals.hideSoftKeyboard(mActivity);
163                  });
164
165         Data.foundTransactionItemIndex.observe(getViewLifecycleOwner(), pos -> {
166             Logger.debug("go-to-date", String.format(Locale.US, "Found pos %d", pos));
167             if (pos != null) {
168                 root.scrollToPosition(pos);
169                 // reset the value to avoid re-notification upon reconfiguration or app restart
170                 Data.foundTransactionItemIndex.setValue(null);
171             }
172         });
173     }
174     private void onAccountNameFilterChanged(String accName) {
175         final String fieldText = accNameFilter.getText()
176                                               .toString();
177         if ((accName == null) && (fieldText.equals("")))
178             return;
179
180         if (accNameFilter != null) {
181             accNameFilter.setText(accName, false);
182         }
183         final boolean filterActive = (accName != null) && !accName.isEmpty();
184         if (vAccountFilter != null) {
185             vAccountFilter.setVisibility(filterActive ? View.VISIBLE : View.GONE);
186         }
187         if (menuTransactionListFilter != null)
188             menuTransactionListFilter.setVisible(!filterActive);
189
190         TransactionListViewModel.scheduleTransactionListReload();
191
192     }
193     @Override
194     public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) {
195         inflater.inflate(R.menu.transaction_list, menu);
196
197         menuTransactionListFilter = menu.findItem(R.id.menu_transaction_list_filter);
198         if ((menuTransactionListFilter == null))
199             throw new AssertionError();
200
201         if ((Data.accountFilter.getValue() != null) ||
202             (vAccountFilter.getVisibility() == View.VISIBLE))
203         {
204             menuTransactionListFilter.setVisible(false);
205         }
206
207         super.onCreateOptionsMenu(menu, inflater);
208
209         menuTransactionListFilter.setOnMenuItemClickListener(item -> {
210             vAccountFilter.setVisibility(View.VISIBLE);
211             if (menuTransactionListFilter != null)
212                 menuTransactionListFilter.setVisible(false);
213             accNameFilter.requestFocus();
214             InputMethodManager imm =
215                     (InputMethodManager) mActivity.getSystemService(INPUT_METHOD_SERVICE);
216             imm.showSoftInput(accNameFilter, 0);
217
218             return true;
219         });
220
221         menu.findItem(R.id.menu_go_to_date)
222             .setOnMenuItemClickListener(item -> {
223                 DatePickerFragment picker = new DatePickerFragment();
224                 picker.setOnDatePickedListener(this);
225                 picker.setDateRange(Data.earliestTransactionDate.getValue(),
226                         Data.latestTransactionDate.getValue());
227                 picker.show(requireActivity().getSupportFragmentManager(), null);
228                 return true;
229             });
230     }
231     @Override
232     public void onDatePicked(int year, int month, int day) {
233         RecyclerView list = requireActivity().findViewById(R.id.transaction_root);
234         AsyncTask<SimpleDate, Void, Integer> finder = new TransactionDateFinder();
235
236         finder.execute(new SimpleDate(year, month + 1, day));
237     }
238 }