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