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