]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionItemHolder.java
more pronounced day/month delimiters in the transaction list
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / NewTransactionItemHolder.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.activity;
19
20 import android.annotation.SuppressLint;
21 import android.graphics.Typeface;
22 import android.text.Editable;
23 import android.text.TextWatcher;
24 import android.view.Gravity;
25 import android.view.View;
26 import android.view.ViewGroup;
27 import android.view.inputmethod.EditorInfo;
28 import android.widget.AutoCompleteTextView;
29 import android.widget.EditText;
30 import android.widget.FrameLayout;
31 import android.widget.TextView;
32
33 import androidx.annotation.ColorInt;
34 import androidx.annotation.NonNull;
35 import androidx.appcompat.app.AppCompatActivity;
36 import androidx.constraintlayout.widget.ConstraintLayout;
37 import androidx.lifecycle.Observer;
38 import androidx.recyclerview.widget.RecyclerView;
39
40 import net.ktnx.mobileledger.R;
41 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
42 import net.ktnx.mobileledger.model.Currency;
43 import net.ktnx.mobileledger.model.Data;
44 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
45 import net.ktnx.mobileledger.model.MobileLedgerProfile;
46 import net.ktnx.mobileledger.ui.CurrencySelectorFragment;
47 import net.ktnx.mobileledger.ui.DatePickerFragment;
48 import net.ktnx.mobileledger.ui.TextViewClearHelper;
49 import net.ktnx.mobileledger.utils.DimensionUtils;
50 import net.ktnx.mobileledger.utils.Logger;
51 import net.ktnx.mobileledger.utils.MLDB;
52 import net.ktnx.mobileledger.utils.Misc;
53 import net.ktnx.mobileledger.utils.SimpleDate;
54
55 import java.text.DecimalFormatSymbols;
56 import java.text.ParseException;
57 import java.util.Date;
58 import java.util.Locale;
59
60 import static net.ktnx.mobileledger.ui.activity.NewTransactionModel.ItemType;
61
62 class NewTransactionItemHolder extends RecyclerView.ViewHolder
63         implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback {
64     private final String decimalDot;
65     private final TextView tvCurrency;
66     private final Observer<Boolean> showCommentsObserver;
67     private final TextView tvTransactionComment;
68     private String decimalSeparator;
69     private NewTransactionModel.Item item;
70     private TextView tvDate;
71     private AutoCompleteTextView tvDescription;
72     private TextView tvDummy;
73     private AutoCompleteTextView tvAccount;
74     private TextView tvComment;
75     private EditText tvAmount;
76     private ViewGroup lHead;
77     private ViewGroup lAccount;
78     private FrameLayout lPadding;
79     private MobileLedgerProfile mProfile;
80     private Date date;
81     private Observer<SimpleDate> dateObserver;
82     private Observer<String> descriptionObserver;
83     private Observer<String> transactionCommentObserver;
84     private Observer<String> hintObserver;
85     private Observer<Integer> focusedAccountObserver;
86     private Observer<Integer> accountCountObserver;
87     private Observer<Boolean> editableObserver;
88     private Observer<Currency.Position> currencyPositionObserver;
89     private Observer<Boolean> currencyGapObserver;
90     private Observer<Locale> localeObserver;
91     private Observer<Currency> currencyObserver;
92     private Observer<Boolean> showCurrencyObserver;
93     private Observer<String> commentObserver;
94     private Observer<Boolean> amountValidityObserver;
95     private boolean inUpdate = false;
96     private boolean syncingData = false;
97     private View commentButton;
98     //TODO multiple amounts with different currencies per posting
99     NewTransactionItemHolder(@NonNull View itemView, NewTransactionItemsAdapter adapter) {
100         super(itemView);
101         lAccount = itemView.findViewById(R.id.ntr_account);
102         tvAccount = lAccount.findViewById(R.id.account_row_acc_name);
103         tvComment = lAccount.findViewById(R.id.comment);
104         tvTransactionComment = itemView.findViewById(R.id.transaction_comment);
105         new TextViewClearHelper().attachToTextView((EditText) tvComment);
106         commentButton = lAccount.findViewById(R.id.comment_button);
107         tvAmount = itemView.findViewById(R.id.account_row_acc_amounts);
108         tvCurrency = itemView.findViewById(R.id.currency);
109         tvDate = itemView.findViewById(R.id.new_transaction_date);
110         tvDescription = itemView.findViewById(R.id.new_transaction_description);
111         tvDummy = itemView.findViewById(R.id.dummy_text);
112         lHead = itemView.findViewById(R.id.ntr_data);
113         lPadding = itemView.findViewById(R.id.ntr_padding);
114         final View commentLayout = itemView.findViewById(R.id.comment_layout);
115         final View transactionCommentLayout =
116                 itemView.findViewById(R.id.transaction_comment_layout);
117
118         tvDescription.setNextFocusForwardId(View.NO_ID);
119         tvAccount.setNextFocusForwardId(View.NO_ID);
120         tvAmount.setNextFocusForwardId(View.NO_ID); // magic!
121
122         tvDate.setOnClickListener(v -> pickTransactionDate());
123
124         commentButton.setOnClickListener(v -> {
125             tvComment.setVisibility(View.VISIBLE);
126             tvComment.requestFocus();
127         });
128
129         transactionCommentLayout.findViewById(R.id.comment_button)
130                                 .setOnClickListener(v -> {
131                                     tvTransactionComment.setVisibility(View.VISIBLE);
132                                     tvTransactionComment.requestFocus();
133                                 });
134
135         mProfile = Data.profile.getValue();
136         if (mProfile == null)
137             throw new AssertionError();
138
139         View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
140             final int id = v.getId();
141             if (hasFocus) {
142                 boolean wasSyncing = syncingData;
143                 syncingData = true;
144                 try {
145                     final int pos = getAdapterPosition();
146                     adapter.updateFocusedItem(pos);
147                     switch (id) {
148                         case R.id.account_row_acc_name:
149                             adapter.noteFocusIsOnAccount(pos);
150                             break;
151                         case R.id.account_row_acc_amounts:
152                             adapter.noteFocusIsOnAmount(pos);
153                             break;
154                         case R.id.comment:
155                             adapter.noteFocusIsOnComment(pos);
156                             break;
157                         case R.id.transaction_comment:
158                             adapter.noteFocusIsOnTransactionComment(pos);
159                             break;
160                         case R.id.new_transaction_description:
161                             adapter.noteFocusIsOnDescription(pos);
162                             break;
163                     }
164                 }
165                 finally {
166                     syncingData = wasSyncing;
167                 }
168             }
169
170             if (id == R.id.comment) {
171                 commentFocusChanged(tvComment, hasFocus);
172             }
173             else if (id == R.id.transaction_comment) {
174                 commentFocusChanged(tvTransactionComment, hasFocus);
175             }
176         };
177
178         tvDescription.setOnFocusChangeListener(focusMonitor);
179         tvAccount.setOnFocusChangeListener(focusMonitor);
180         tvAmount.setOnFocusChangeListener(focusMonitor);
181         tvComment.setOnFocusChangeListener(focusMonitor);
182         tvTransactionComment.setOnFocusChangeListener(focusMonitor);
183
184         MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
185                 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
186         MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
187                 "name", true, this, mProfile);
188
189         decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
190                                                               .getMonetaryDecimalSeparator());
191         localeObserver = locale -> {
192             decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance(locale)
193                                                                   .getMonetaryDecimalSeparator());
194         };
195
196         decimalDot = ".";
197
198         final TextWatcher tw = new TextWatcher() {
199             @Override
200             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
201             }
202
203             @Override
204             public void onTextChanged(CharSequence s, int start, int before, int count) {
205             }
206
207             @Override
208             public void afterTextChanged(Editable s) {
209 //                debug("input", "text changed");
210                 if (inUpdate)
211                     return;
212
213                 Logger.debug("textWatcher", "calling syncData()");
214                 syncData();
215                 Logger.debug("textWatcher",
216                         "syncData() returned, checking if transaction is submittable");
217                 adapter.checkTransactionSubmittable();
218                 Logger.debug("textWatcher", "done");
219             }
220         };
221         final TextWatcher amountWatcher = new TextWatcher() {
222             @Override
223             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
224                 Logger.debug("num",
225                         String.format(Locale.US, "beforeTextChanged: start=%d, count=%d, after=%d",
226                                 start, count, after));
227             }
228             @Override
229             public void onTextChanged(CharSequence s, int start, int before, int count) {}
230             @Override
231             public void afterTextChanged(Editable s) {
232
233                 if (syncData())
234                     adapter.checkTransactionSubmittable();
235             }
236         };
237         tvDescription.addTextChangedListener(tw);
238         tvTransactionComment.addTextChangedListener(tw);
239         tvAccount.addTextChangedListener(tw);
240         tvComment.addTextChangedListener(tw);
241         tvAmount.addTextChangedListener(amountWatcher);
242
243         tvCurrency.setOnClickListener(v -> {
244             CurrencySelectorFragment cpf = new CurrencySelectorFragment();
245             cpf.showPositionAndPadding();
246             cpf.setOnCurrencySelectedListener(c -> item.setCurrency(c));
247             final AppCompatActivity activity = (AppCompatActivity) v.getContext();
248             cpf.show(activity.getSupportFragmentManager(), "currency-selector");
249         });
250
251         dateObserver = date -> {
252             if (syncingData)
253                 return;
254             syncingData = true;
255             try {
256                 tvDate.setText(item.getFormattedDate());
257             }
258             finally {
259                 syncingData = false;
260             }
261         };
262         descriptionObserver = description -> {
263             if (syncingData)
264                 return;
265             syncingData = true;
266             try {
267                 tvDescription.setText(description);
268             }
269             finally {
270                 syncingData = false;
271             }
272         };
273         transactionCommentObserver = transactionComment -> {
274             final View focusedView = tvTransactionComment.findFocus();
275             tvTransactionComment.setTypeface(null,
276                     (focusedView == tvTransactionComment) ? Typeface.NORMAL : Typeface.ITALIC);
277             tvTransactionComment.setVisibility(((focusedView != tvTransactionComment) &&
278                                                 Misc.isEmptyOrNull(transactionComment))
279                                                ? View.INVISIBLE : View.VISIBLE);
280
281         };
282         hintObserver = hint -> {
283             if (syncingData)
284                 return;
285             syncingData = true;
286             try {
287                 if (hint == null)
288                     tvAmount.setHint(R.string.zero_amount);
289                 else
290                     tvAmount.setHint(hint);
291             }
292             finally {
293                 syncingData = false;
294             }
295         };
296         editableObserver = this::setEditable;
297         commentFocusChanged(tvTransactionComment, false);
298         commentFocusChanged(tvComment, false);
299         focusedAccountObserver = index -> {
300             if ((index == null) || !index.equals(getAdapterPosition()) || itemView.hasFocus())
301                 return;
302
303             switch (item.getType()) {
304                 case generalData:
305                     // bad idea - double pop-up, and not really necessary.
306                     // the user can tap the input to get the calendar
307                     //if (!tvDate.hasFocus()) tvDate.requestFocus();
308                     switch (item.getFocusedElement()) {
309                         case TransactionComment:
310                             tvTransactionComment.setVisibility(View.VISIBLE);
311                             tvTransactionComment.requestFocus();
312                             break;
313                         case Description:
314                             boolean focused = tvDescription.requestFocus();
315                             tvDescription.dismissDropDown();
316                             if (focused)
317                                 Misc.showSoftKeyboard(
318                                         (NewTransactionActivity) tvDescription.getContext());
319                             break;
320                     }
321                     break;
322                 case transactionRow:
323                     switch (item.getFocusedElement()) {
324                         case Amount:
325                             tvAmount.requestFocus();
326                             break;
327                         case Comment:
328                             tvComment.setVisibility(View.VISIBLE);
329                             tvComment.requestFocus();
330                             break;
331                         case Account:
332                             boolean focused = tvAccount.requestFocus();
333                             tvAccount.dismissDropDown();
334                             if (focused)
335                                 Misc.showSoftKeyboard(
336                                         (NewTransactionActivity) tvAccount.getContext());
337                             break;
338                     }
339
340                     break;
341             }
342         };
343         accountCountObserver = count -> {
344             final int adapterPosition = getAdapterPosition();
345             final int layoutPosition = getLayoutPosition();
346             Logger.debug("holder",
347                     String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
348                             adapterPosition, layoutPosition, item.getType()
349                                                                  .toString()
350                                                                  .concat(item.getType() ==
351                                                                          ItemType.transactionRow
352                                                                          ? String.format(Locale.US,
353                                                                          "'%s'=%s",
354                                                                          item.getAccount()
355                                                                              .getAccountName(),
356                                                                          item.getAccount()
357                                                                              .isAmountSet()
358                                                                          ? String.format(Locale.US,
359                                                                                  "%.2f",
360                                                                                  item.getAccount()
361                                                                                      .getAmount())
362                                                                          : "unset") : "")));
363             if (adapterPosition == count)
364                 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
365             else
366                 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
367         };
368
369         currencyObserver = currency -> {
370             setCurrency(currency);
371             adapter.checkTransactionSubmittable();
372         };
373
374         currencyGapObserver =
375                 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
376                         hasGap);
377
378         currencyPositionObserver =
379                 position -> updateCurrencyPositionAndPadding(position, Data.currencyGap.getValue());
380
381         showCurrencyObserver = showCurrency -> {
382             if (showCurrency) {
383                 tvCurrency.setVisibility(View.VISIBLE);
384             }
385             else {
386                 tvCurrency.setVisibility(View.GONE);
387                 item.setCurrency(null);
388             }
389         };
390
391         commentObserver = comment -> {
392             final View focusedView = tvComment.findFocus();
393             tvComment.setTypeface(null,
394                     (focusedView == tvComment) ? Typeface.NORMAL : Typeface.ITALIC);
395             tvComment.setVisibility(
396                     ((focusedView != tvComment) && Misc.isEmptyOrNull(comment)) ? View.INVISIBLE
397                                                                                 : View.VISIBLE);
398         };
399
400         showCommentsObserver = show -> {
401             final View amountLayout = itemView.findViewById(R.id.amount_layout);
402             ConstraintLayout.LayoutParams amountLayoutParams =
403                     (ConstraintLayout.LayoutParams) amountLayout.getLayoutParams();
404             ConstraintLayout.LayoutParams accountParams =
405                     (ConstraintLayout.LayoutParams) tvAccount.getLayoutParams();
406             if (show) {
407                 accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
408                 accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
409
410                 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
411                 amountLayoutParams.topToBottom = tvAccount.getId();
412
413                 commentLayout.setVisibility(View.VISIBLE);
414             }
415             else {
416                 accountParams.endToStart = amountLayout.getId();
417                 accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
418
419                 amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
420                 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
421
422                 commentLayout.setVisibility(View.GONE);
423             }
424
425             tvAccount.setLayoutParams(accountParams);
426             amountLayout.setLayoutParams(amountLayoutParams);
427
428             transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
429         };
430
431         amountValidityObserver = valid -> {
432             tvAmount.setCompoundDrawablesRelativeWithIntrinsicBounds(
433                     valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
434             tvAmount.setMinEms(valid ? 4 : 5);
435         };
436     }
437     private void commentFocusChanged(TextView textView, boolean hasFocus) {
438         @ColorInt int textColor;
439         textColor = tvDummy.getTextColors()
440                            .getDefaultColor();
441         if (hasFocus) {
442             textView.setTypeface(null, Typeface.NORMAL);
443             textView.setHint(R.string.transaction_account_comment_hint);
444         }
445         else {
446             int alpha = (textColor >> 24 & 0xff);
447             alpha = 3 * alpha / 4;
448             textColor = (alpha << 24) | (0x00ffffff & textColor);
449             textView.setTypeface(null, Typeface.ITALIC);
450             textView.setHint("");
451             if (Misc.isEmptyOrNull(textView.getText())) {
452                 textView.setVisibility(View.INVISIBLE);
453             }
454         }
455         textView.setTextColor(textColor);
456
457     }
458     private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
459         ConstraintLayout.LayoutParams amountLP =
460                 (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
461         ConstraintLayout.LayoutParams currencyLP =
462                 (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
463
464         if (position == Currency.Position.before) {
465             currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
466             currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
467
468             amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
469             amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
470             amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
471             amountLP.startToEnd = tvCurrency.getId();
472
473             tvCurrency.setGravity(Gravity.END);
474         }
475         else {
476             currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
477             currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
478
479             amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
480             amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
481             amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
482             amountLP.endToStart = tvCurrency.getId();
483
484             tvCurrency.setGravity(Gravity.START);
485         }
486
487         amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
488         currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
489
490         tvAmount.setLayoutParams(amountLP);
491         tvCurrency.setLayoutParams(currencyLP);
492
493         // distance between the amount and the currency symbol
494         int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
495
496         if (position == Currency.Position.before) {
497             tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
498         }
499         else {
500             tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
501         }
502     }
503     private void setCurrencyString(String currency) {
504         @ColorInt int textColor = tvDummy.getTextColors()
505                                          .getDefaultColor();
506         if ((currency == null) || currency.isEmpty()) {
507             tvCurrency.setText(R.string.currency_symbol);
508             int alpha = (textColor >> 24) & 0xff;
509             alpha = alpha * 3 / 4;
510             tvCurrency.setTextColor((alpha << 24) | (0x00ffffff & textColor));
511         }
512         else {
513             tvCurrency.setText(currency);
514             tvCurrency.setTextColor(textColor);
515         }
516     }
517     private void setCurrency(Currency currency) {
518         setCurrencyString((currency == null) ? null : currency.getName());
519     }
520     private void setEditable(Boolean editable) {
521         tvDate.setEnabled(editable);
522         tvDescription.setEnabled(editable);
523         tvAccount.setEnabled(editable);
524         tvAmount.setEnabled(editable);
525     }
526     private void beginUpdates() {
527         if (inUpdate)
528             throw new RuntimeException("Already in update mode");
529         inUpdate = true;
530     }
531     private void endUpdates() {
532         if (!inUpdate)
533             throw new RuntimeException("Not in update mode");
534         inUpdate = false;
535     }
536     /**
537      * syncData()
538      * <p>
539      * Stores the data from the UI elements into the model item
540      * Returns true if there were changes made that suggest transaction has to be
541      * checked for being submittable
542      */
543     private boolean syncData() {
544         if (item == null)
545             return false;
546
547         if (syncingData) {
548             Logger.debug("new-trans", "skipping syncData() loop");
549             return false;
550         }
551
552         syncingData = true;
553
554         try {
555             switch (item.getType()) {
556                 case generalData:
557                     item.setDate(String.valueOf(tvDate.getText()));
558                     item.setDescription(String.valueOf(tvDescription.getText()));
559                     item.setTransactionComment(String.valueOf(tvTransactionComment.getText()));
560                     break;
561                 case transactionRow:
562                     final LedgerTransactionAccount account = item.getAccount();
563                     account.setAccountName(String.valueOf(tvAccount.getText()));
564
565                     item.setComment(String.valueOf(tvComment.getText()));
566
567                     String amount = String.valueOf(tvAmount.getText());
568                     amount = amount.trim();
569
570                     if (amount.isEmpty()) {
571                         account.resetAmount();
572                         item.validateAmount();
573                     }
574                     else {
575                         try {
576                             amount = amount.replace(decimalSeparator, decimalDot);
577                             account.setAmount(Float.parseFloat(amount));
578                             item.validateAmount();
579                         }
580                         catch (NumberFormatException e) {
581                             Logger.debug("new-trans", String.format(
582                                     "assuming amount is not set due to number format exception. " +
583                                     "input was '%s'", amount));
584                             account.invalidateAmount();
585                             item.invalidateAmount();
586                         }
587                         final String curr = String.valueOf(tvCurrency.getText());
588                         if (curr.equals(tvCurrency.getContext()
589                                                   .getResources()
590                                                   .getString(R.string.currency_symbol)) ||
591                             curr.isEmpty())
592                             account.setCurrency(null);
593                         else
594                             account.setCurrency(curr);
595                     }
596
597                     break;
598                 case bottomFiller:
599                     throw new RuntimeException("Should not happen");
600             }
601
602             return true;
603         }
604         catch (ParseException e) {
605             throw new RuntimeException("Should not happen", e);
606         }
607         finally {
608             syncingData = false;
609         }
610     }
611     private void pickTransactionDate() {
612         DatePickerFragment picker = new DatePickerFragment();
613         picker.setFutureDates(mProfile.getFutureDates());
614         picker.setOnDatePickedListener(this);
615         picker.setCurrentDateFromText(tvDate.getText());
616         picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
617                 null);
618     }
619     /**
620      * setData
621      *
622      * @param item updates the UI elements with the data from the model item
623      */
624     @SuppressLint("DefaultLocale")
625     public void setData(NewTransactionModel.Item item) {
626         beginUpdates();
627         try {
628             if (this.item != null && !this.item.equals(item)) {
629                 this.item.stopObservingDate(dateObserver);
630                 this.item.stopObservingDescription(descriptionObserver);
631                 this.item.stopObservingTransactionComment(transactionCommentObserver);
632                 this.item.stopObservingAmountHint(hintObserver);
633                 this.item.stopObservingEditableFlag(editableObserver);
634                 this.item.getModel()
635                          .stopObservingFocusedItem(focusedAccountObserver);
636                 this.item.getModel()
637                          .stopObservingAccountCount(accountCountObserver);
638                 Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
639                 Data.currencyGap.removeObserver(currencyGapObserver);
640                 Data.locale.removeObserver(localeObserver);
641                 this.item.stopObservingCurrency(currencyObserver);
642                 this.item.getModel().showCurrency.removeObserver(showCurrencyObserver);
643                 this.item.stopObservingComment(commentObserver);
644                 this.item.getModel().showComments.removeObserver(showCommentsObserver);
645                 this.item.stopObservingAmountValidity(amountValidityObserver);
646
647                 this.item = null;
648             }
649
650             switch (item.getType()) {
651                 case generalData:
652                     tvDate.setText(item.getFormattedDate());
653                     tvDescription.setText(item.getDescription());
654                     tvTransactionComment.setText(item.getTransactionComment());
655                     lHead.setVisibility(View.VISIBLE);
656                     lAccount.setVisibility(View.GONE);
657                     lPadding.setVisibility(View.GONE);
658                     setEditable(true);
659                     break;
660                 case transactionRow:
661                     LedgerTransactionAccount acc = item.getAccount();
662                     tvAccount.setText(acc.getAccountName());
663                     tvComment.setText(acc.getComment());
664                     if (acc.isAmountSet()) {
665                         tvAmount.setText(String.format("%1.2f", acc.getAmount()));
666                     }
667                     else {
668                         tvAmount.setText("");
669 //                        tvAmount.setHint(R.string.zero_amount);
670                     }
671                     tvAmount.setHint(item.getAmountHint());
672                     setCurrencyString(acc.getCurrency());
673                     lHead.setVisibility(View.GONE);
674                     lAccount.setVisibility(View.VISIBLE);
675                     lPadding.setVisibility(View.GONE);
676                     setEditable(true);
677                     break;
678                 case bottomFiller:
679                     lHead.setVisibility(View.GONE);
680                     lAccount.setVisibility(View.GONE);
681                     lPadding.setVisibility(View.VISIBLE);
682                     setEditable(false);
683                     break;
684             }
685             if (this.item == null) { // was null or has changed
686                 this.item = item;
687                 final NewTransactionActivity activity =
688                         (NewTransactionActivity) tvDescription.getContext();
689
690                 if (!item.isOfType(ItemType.bottomFiller)) {
691                     item.observeEditableFlag(activity, editableObserver);
692                     item.getModel()
693                         .observeFocusedItem(activity, focusedAccountObserver);
694                     item.getModel()
695                         .observeShowComments(activity, showCommentsObserver);
696                 }
697                 switch (item.getType()) {
698                     case generalData:
699                         item.observeDate(activity, dateObserver);
700                         item.observeDescription(activity, descriptionObserver);
701                         item.observeTransactionComment(activity, transactionCommentObserver);
702                         break;
703                     case transactionRow:
704                         item.observeAmountHint(activity, hintObserver);
705                         Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
706                         Data.currencyGap.observe(activity, currencyGapObserver);
707                         Data.locale.observe(activity, localeObserver);
708                         item.observeCurrency(activity, currencyObserver);
709                         item.getModel().showCurrency.observe(activity, showCurrencyObserver);
710                         item.observeComment(activity, commentObserver);
711                         item.getModel()
712                             .observeAccountCount(activity, accountCountObserver);
713                         item.observeAmountValidity(activity, amountValidityObserver);
714                         break;
715                 }
716             }
717         }
718         finally {
719             endUpdates();
720         }
721     }
722     @Override
723     public void onDatePicked(int year, int month, int day) {
724         item.setDate(new SimpleDate(year, month+1, day));
725         boolean focused = tvDescription.requestFocus();
726         if (focused)
727             Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
728
729     }
730     @Override
731     public void descriptionSelected(String description) {
732         tvAccount.setText(description);
733         tvAmount.requestFocus(View.FOCUS_FORWARD);
734     }
735 }