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.constraintlayout.widget.ConstraintLayout;
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 ConstraintLayout 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.setOnFocusChangeListener((v, hasFocus) -> {
91 pickTransactionDate();
93 tvDate.setOnClickListener(v -> pickTransactionDate());
95 mProfile = Data.profile.getValue();
97 throw new AssertionError();
99 MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
100 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
101 MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
102 "name", true, this, mProfile);
104 // FIXME: react on configuration (locale) changes
105 decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
106 .getMonetaryDecimalSeparator());
109 final TextWatcher tw = new TextWatcher() {
111 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
115 public void onTextChanged(CharSequence s, int start, int before, int count) {
119 public void afterTextChanged(Editable s) {
120 // debug("input", "text changed");
124 Logger.debug("textWatcher", "calling syncData()");
126 Logger.debug("textWatcher",
127 "syncData() returned, checking if transaction is submittable");
128 adapter.model.checkTransactionSubmittable(adapter);
129 Logger.debug("textWatcher", "done");
132 final TextWatcher amountWatcher = new TextWatcher() {
134 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
137 public void onTextChanged(CharSequence s, int start, int before, int count) {
141 public void afterTextChanged(Editable s) {
142 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
143 // only one decimal separator is allowed
144 // plus and minus are allowed only at the beginning
145 String val = s.toString();
147 tvAmount.setKeyListener(DigitsKeyListener.getInstance(
148 "0123456789+-" + decimalSeparator + decimalDot));
149 else if (val.contains(decimalSeparator) || val.contains(decimalDot))
150 tvAmount.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
152 tvAmount.setKeyListener(DigitsKeyListener.getInstance(
153 "0123456789" + decimalSeparator + decimalDot));
156 adapter.model.checkTransactionSubmittable(adapter);
160 tvDescription.addTextChangedListener(tw);
161 tvAccount.addTextChangedListener(tw);
162 tvAmount.addTextChangedListener(amountWatcher);
164 // FIXME: react on locale changes
165 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
166 tvAmount.setKeyListener(DigitsKeyListener.getInstance(Locale.getDefault(), true, true));
168 tvAmount.setKeyListener(
169 DigitsKeyListener.getInstance("0123456789+-" + decimalSeparator + decimalDot));
171 dateObserver = date -> {
176 tvDate.setText(item.getFormattedDate());
182 descriptionObserver = description -> {
187 tvDescription.setText(description);
193 hintObserver = hint -> {
199 hint = tvAmount.getResources()
200 .getString(R.string.zero_amount);
201 tvAmount.setHint(hint);
207 editableObserver = this::setEditable;
208 focusedAccountObserver = index -> {
209 if ((index != null) && index.equals(getAdapterPosition())) {
210 switch (item.getType()) {
212 // bad idea - double pop-up, and not really necessary.
213 // the user can tap the input to get the calendar
214 //if (!tvDate.hasFocus()) tvDate.requestFocus();
215 boolean focused = tvDescription.requestFocus();
216 tvDescription.dismissDropDown();
218 Misc.showSoftKeyboard(
219 (NewTransactionActivity) tvDescription.getContext());
222 focused = tvAccount.requestFocus();
223 tvAccount.dismissDropDown();
225 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
231 accountCountObserver = count -> {
232 final int adapterPosition = getAdapterPosition();
233 final int layoutPosition = getLayoutPosition();
234 Logger.debug("holder",
235 String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
236 adapterPosition, layoutPosition, item.getType()
238 .concat(item.getType() ==
239 NewTransactionModel.ItemType.transactionRow
240 ? String.format(Locale.US,
246 ? String.format(Locale.US,
251 if (adapterPosition == count)
252 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
254 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
257 private void setEditable(Boolean editable) {
258 tvDate.setEnabled(editable);
259 tvDescription.setEnabled(editable);
260 tvAccount.setEnabled(editable);
261 tvAmount.setEnabled(editable);
263 private void beginUpdates() {
265 throw new RuntimeException("Already in update mode");
268 private void endUpdates() {
270 throw new RuntimeException("Not in update mode");
276 * Stores the data from the UI elements into the model item
278 private void syncData() {
283 Logger.debug("new-trans", "skipping syncData() loop");
290 switch (item.getType()) {
292 item.setDate(String.valueOf(tvDate.getText()));
293 item.setDescription(String.valueOf(tvDescription.getText()));
297 .setAccountName(String.valueOf(tvAccount.getText()));
299 // TODO: handle multiple amounts
300 String amount = String.valueOf(tvAmount.getText());
301 amount = amount.trim();
303 if (amount.isEmpty()) {
309 amount = amount.replace(decimalSeparator, decimalDot);
311 .setAmount(Float.parseFloat(amount));
313 catch (NumberFormatException e) {
314 Logger.debug("new-trans", String.format(
315 "assuming amount is not set due to number format exception. " +
325 throw new RuntimeException("Should not happen");
332 private void pickTransactionDate() {
333 DatePickerFragment picker = new DatePickerFragment();
334 picker.setOnDatePickedListener(this);
335 picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
341 * @param item updates the UI elements with the data from the model item
343 @SuppressLint("DefaultLocale")
344 public void setData(NewTransactionModel.Item item) {
347 if (this.item != null && !this.item.equals(item)) {
348 this.item.stopObservingDate(dateObserver);
349 this.item.stopObservingDescription(descriptionObserver);
350 this.item.stopObservingAmountHint(hintObserver);
351 this.item.stopObservingEditableFlag(editableObserver);
353 .stopObservingFocusedItem(focusedAccountObserver);
355 .stopObservingAccountCount(accountCountObserver);
360 switch (item.getType()) {
362 tvDate.setText(item.getFormattedDate());
363 tvDescription.setText(item.getDescription());
364 lHead.setVisibility(View.VISIBLE);
365 lAccount.setVisibility(View.GONE);
366 lPadding.setVisibility(View.GONE);
370 LedgerTransactionAccount acc = item.getAccount();
371 tvAccount.setText(acc.getAccountName());
373 acc.isAmountSet() ? String.format("%1.2f", acc.getAmount()) : "");
374 lHead.setVisibility(View.GONE);
375 lAccount.setVisibility(View.VISIBLE);
376 lPadding.setVisibility(View.GONE);
380 lHead.setVisibility(View.GONE);
381 lAccount.setVisibility(View.GONE);
382 lPadding.setVisibility(View.VISIBLE);
387 if (this.item == null) { // was null or has changed
389 final NewTransactionActivity activity =
390 (NewTransactionActivity) tvDescription.getContext();
391 item.observeDate(activity, dateObserver);
392 item.observeDescription(activity, descriptionObserver);
393 item.observeAmountHint(activity, hintObserver);
394 item.observeEditableFlag(activity, editableObserver);
396 .observeFocusedItem(activity, focusedAccountObserver);
398 .observeAccountCount(activity, accountCountObserver);
406 public void onDatePicked(int year, int month, int day) {
407 final Calendar c = GregorianCalendar.getInstance();
408 c.set(year, month, day);
409 item.setDate(c.getTime());
410 boolean focused = tvDescription.requestFocus();
412 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
416 public void descriptionSelected(String description) {
417 tvAccount.setText(description);
418 tvAmount.requestFocus(View.FOCUS_FORWARD);