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.annotation.SuppressLint;
21 import android.os.Build;
22 import android.text.Editable;
23 import android.text.TextWatcher;
24 import android.text.method.DigitsKeyListener;
25 import android.view.View;
26 import android.view.inputmethod.EditorInfo;
27 import android.widget.AutoCompleteTextView;
28 import android.widget.FrameLayout;
29 import android.widget.LinearLayout;
30 import android.widget.TextView;
32 import androidx.annotation.NonNull;
33 import androidx.appcompat.widget.LinearLayoutCompat;
34 import androidx.lifecycle.Observer;
35 import androidx.recyclerview.widget.RecyclerView;
37 import net.ktnx.mobileledger.R;
38 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
39 import net.ktnx.mobileledger.model.Data;
40 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
41 import net.ktnx.mobileledger.model.MobileLedgerProfile;
42 import net.ktnx.mobileledger.ui.DatePickerFragment;
43 import net.ktnx.mobileledger.utils.Logger;
44 import net.ktnx.mobileledger.utils.MLDB;
45 import net.ktnx.mobileledger.utils.Misc;
47 import java.text.DecimalFormatSymbols;
48 import java.util.Calendar;
49 import java.util.Date;
50 import java.util.GregorianCalendar;
51 import java.util.Locale;
53 class NewTransactionItemHolder extends RecyclerView.ViewHolder
54 implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback {
55 private final String decimalSeparator;
56 private final String decimalDot;
57 private NewTransactionModel.Item item;
58 private TextView tvDate;
59 private AutoCompleteTextView tvDescription;
60 private AutoCompleteTextView tvAccount;
61 private TextView tvAmount;
62 private LinearLayoutCompat lHead;
63 private LinearLayout lAccount;
64 private FrameLayout lPadding;
65 private MobileLedgerProfile mProfile;
67 private Observer<Date> dateObserver;
68 private Observer<String> descriptionObserver;
69 private Observer<String> hintObserver;
70 private Observer<Integer> focusedAccountObserver;
71 private Observer<Integer> accountCountObserver;
72 private Observer<Boolean> editableObserver;
73 private boolean inUpdate = false;
74 private boolean syncingData = false;
75 NewTransactionItemHolder(@NonNull View itemView, NewTransactionItemsAdapter adapter) {
77 tvAccount = itemView.findViewById(R.id.account_row_acc_name);
78 tvAmount = itemView.findViewById(R.id.account_row_acc_amounts);
79 tvDate = itemView.findViewById(R.id.new_transaction_date);
80 tvDescription = itemView.findViewById(R.id.new_transaction_description);
81 lHead = itemView.findViewById(R.id.ntr_data);
82 lAccount = itemView.findViewById(R.id.ntr_account);
83 lPadding = itemView.findViewById(R.id.ntr_padding);
85 tvDescription.setNextFocusForwardId(View.NO_ID);
86 tvAccount.setNextFocusForwardId(View.NO_ID);
87 tvAmount.setNextFocusForwardId(View.NO_ID); // magic!
89 tvDate.setOnClickListener(v -> pickTransactionDate());
91 mProfile = Data.profile.getValue();
93 throw new AssertionError();
95 MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
96 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
97 MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
98 "name", true, this, mProfile);
100 // FIXME: react on configuration (locale) changes
101 decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
102 .getMonetaryDecimalSeparator());
105 final TextWatcher tw = new TextWatcher() {
107 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
111 public void onTextChanged(CharSequence s, int start, int before, int count) {
115 public void afterTextChanged(Editable s) {
116 // debug("input", "text changed");
120 Logger.debug("textWatcher", "calling syncData()");
122 Logger.debug("textWatcher",
123 "syncData() returned, checking if transaction is submittable");
124 adapter.model.checkTransactionSubmittable(adapter);
125 Logger.debug("textWatcher", "done");
128 final TextWatcher amountWatcher = new TextWatcher() {
130 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
133 public void onTextChanged(CharSequence s, int start, int before, int count) {
137 public void afterTextChanged(Editable s) {
138 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
139 // only one decimal separator is allowed
140 // plus and minus are allowed only at the beginning
141 String val = s.toString();
143 tvAmount.setKeyListener(DigitsKeyListener.getInstance(
144 "0123456789+-" + decimalSeparator + decimalDot));
145 else if (val.contains(decimalSeparator) || val.contains(decimalDot))
146 tvAmount.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
148 tvAmount.setKeyListener(DigitsKeyListener.getInstance(
149 "0123456789" + decimalSeparator + decimalDot));
152 adapter.model.checkTransactionSubmittable(adapter);
156 tvDescription.addTextChangedListener(tw);
157 tvAccount.addTextChangedListener(tw);
158 tvAmount.addTextChangedListener(amountWatcher);
160 // FIXME: react on locale changes
161 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
162 tvAmount.setKeyListener(DigitsKeyListener.getInstance(Locale.getDefault(), true, true));
164 tvAmount.setKeyListener(
165 DigitsKeyListener.getInstance("0123456789+-" + decimalSeparator + decimalDot));
167 dateObserver = date -> {
172 tvDate.setText(item.getFormattedDate());
178 descriptionObserver = description -> {
183 tvDescription.setText(description);
189 hintObserver = hint -> {
195 tvAmount.setHint(R.string.zero_amount);
197 tvAmount.setHint(hint);
203 editableObserver = this::setEditable;
204 focusedAccountObserver = index -> {
205 if ((index != null) && index.equals(getAdapterPosition())) {
206 switch (item.getType()) {
208 // bad idea - double pop-up, and not really necessary.
209 // the user can tap the input to get the calendar
210 //if (!tvDate.hasFocus()) tvDate.requestFocus();
211 boolean focused = tvDescription.requestFocus();
212 tvDescription.dismissDropDown();
214 Misc.showSoftKeyboard(
215 (NewTransactionActivity) tvDescription.getContext());
218 focused = tvAccount.requestFocus();
219 tvAccount.dismissDropDown();
221 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
227 accountCountObserver = count -> {
228 final int adapterPosition = getAdapterPosition();
229 final int layoutPosition = getLayoutPosition();
230 Logger.debug("holder",
231 String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
232 adapterPosition, layoutPosition, item.getType()
234 .concat(item.getType() ==
235 NewTransactionModel.ItemType.transactionRow
236 ? String.format(Locale.US,
242 ? String.format(Locale.US,
247 if (adapterPosition == count)
248 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
250 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
253 private void setEditable(Boolean editable) {
254 tvDate.setEnabled(editable);
255 tvDescription.setEnabled(editable);
256 tvAccount.setEnabled(editable);
257 tvAmount.setEnabled(editable);
259 private void beginUpdates() {
261 throw new RuntimeException("Already in update mode");
264 private void endUpdates() {
266 throw new RuntimeException("Not in update mode");
272 * Stores the data from the UI elements into the model item
274 private void syncData() {
279 Logger.debug("new-trans", "skipping syncData() loop");
286 switch (item.getType()) {
288 item.setDate(String.valueOf(tvDate.getText()));
289 item.setDescription(String.valueOf(tvDescription.getText()));
293 .setAccountName(String.valueOf(tvAccount.getText()));
295 // TODO: handle multiple amounts
296 String amount = String.valueOf(tvAmount.getText());
297 amount = amount.trim();
299 if (amount.isEmpty()) {
305 amount = amount.replace(decimalSeparator, decimalDot);
307 .setAmount(Float.parseFloat(amount));
309 catch (NumberFormatException e) {
310 Logger.debug("new-trans", String.format(
311 "assuming amount is not set due to number format exception. " +
312 "input was '%s'", amount));
320 throw new RuntimeException("Should not happen");
327 private void pickTransactionDate() {
328 DatePickerFragment picker = new DatePickerFragment();
329 picker.setOnDatePickedListener(this);
330 picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
336 * @param item updates the UI elements with the data from the model item
338 @SuppressLint("DefaultLocale")
339 public void setData(NewTransactionModel.Item item) {
342 if (this.item != null && !this.item.equals(item)) {
343 this.item.stopObservingDate(dateObserver);
344 this.item.stopObservingDescription(descriptionObserver);
345 this.item.stopObservingAmountHint(hintObserver);
346 this.item.stopObservingEditableFlag(editableObserver);
348 .stopObservingFocusedItem(focusedAccountObserver);
350 .stopObservingAccountCount(accountCountObserver);
355 switch (item.getType()) {
357 tvDate.setText(item.getFormattedDate());
358 tvDescription.setText(item.getDescription());
359 lHead.setVisibility(View.VISIBLE);
360 lAccount.setVisibility(View.GONE);
361 lPadding.setVisibility(View.GONE);
365 LedgerTransactionAccount acc = item.getAccount();
366 tvAccount.setText(acc.getAccountName());
367 if (acc.isAmountSet()) {
368 tvAmount.setText(String.format("%1.2f", acc.getAmount()));
371 tvAmount.setText("");
372 // tvAmount.setHint(R.string.zero_amount);
374 tvAmount.setHint(item.getAmountHint());
375 lHead.setVisibility(View.GONE);
376 lAccount.setVisibility(View.VISIBLE);
377 lPadding.setVisibility(View.GONE);
381 lHead.setVisibility(View.GONE);
382 lAccount.setVisibility(View.GONE);
383 lPadding.setVisibility(View.VISIBLE);
388 if (this.item == null) { // was null or has changed
390 final NewTransactionActivity activity =
391 (NewTransactionActivity) tvDescription.getContext();
392 item.observeDate(activity, dateObserver);
393 item.observeDescription(activity, descriptionObserver);
394 item.observeAmountHint(activity, hintObserver);
395 item.observeEditableFlag(activity, editableObserver);
397 .observeFocusedItem(activity, focusedAccountObserver);
399 .observeAccountCount(activity, accountCountObserver);
407 public void onDatePicked(int year, int month, int day) {
408 final Calendar c = GregorianCalendar.getInstance();
409 c.set(year, month, day);
410 item.setDate(c.getTime());
411 boolean focused = tvDescription.requestFocus();
413 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
417 public void descriptionSelected(String description) {
418 tvAccount.setText(description);
419 tvAmount.requestFocus(View.FOCUS_FORWARD);