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