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.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 tvAmount.setHint(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. " +
316 "input was '%s'", amount));
324 throw new RuntimeException("Should not happen");
331 private void pickTransactionDate() {
332 DatePickerFragment picker = new DatePickerFragment();
333 picker.setOnDatePickedListener(this);
334 picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
340 * @param item updates the UI elements with the data from the model item
342 @SuppressLint("DefaultLocale")
343 public void setData(NewTransactionModel.Item item) {
346 if (this.item != null && !this.item.equals(item)) {
347 this.item.stopObservingDate(dateObserver);
348 this.item.stopObservingDescription(descriptionObserver);
349 this.item.stopObservingAmountHint(hintObserver);
350 this.item.stopObservingEditableFlag(editableObserver);
352 .stopObservingFocusedItem(focusedAccountObserver);
354 .stopObservingAccountCount(accountCountObserver);
359 switch (item.getType()) {
361 tvDate.setText(item.getFormattedDate());
362 tvDescription.setText(item.getDescription());
363 lHead.setVisibility(View.VISIBLE);
364 lAccount.setVisibility(View.GONE);
365 lPadding.setVisibility(View.GONE);
369 LedgerTransactionAccount acc = item.getAccount();
370 tvAccount.setText(acc.getAccountName());
371 if (acc.isAmountSet()) {
372 tvAmount.setText(String.format("%1.2f", acc.getAmount()));
375 tvAmount.setText("");
376 // tvAmount.setHint(R.string.zero_amount);
378 tvAmount.setHint(item.getAmountHint());
379 lHead.setVisibility(View.GONE);
380 lAccount.setVisibility(View.VISIBLE);
381 lPadding.setVisibility(View.GONE);
385 lHead.setVisibility(View.GONE);
386 lAccount.setVisibility(View.GONE);
387 lPadding.setVisibility(View.VISIBLE);
392 if (this.item == null) { // was null or has changed
394 final NewTransactionActivity activity =
395 (NewTransactionActivity) tvDescription.getContext();
396 item.observeDate(activity, dateObserver);
397 item.observeDescription(activity, descriptionObserver);
398 item.observeAmountHint(activity, hintObserver);
399 item.observeEditableFlag(activity, editableObserver);
401 .observeFocusedItem(activity, focusedAccountObserver);
403 .observeAccountCount(activity, accountCountObserver);
411 public void onDatePicked(int year, int month, int day) {
412 final Calendar c = GregorianCalendar.getInstance();
413 c.set(year, month, day);
414 item.setDate(c.getTime());
415 boolean focused = tvDescription.requestFocus();
417 Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
421 public void descriptionSelected(String description) {
422 tvAccount.setText(description);
423 tvAmount.requestFocus(View.FOCUS_FORWARD);