]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionItemHolder.java
16ef747e757d10d1ff130d41f91f725bd1ac2448
[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 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         // FIXME: react on configuration (locale) changes
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             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
365                 tvAmount.setKeyListener(DigitsKeyListener.getInstance(locale, true, true));
366         };
367
368         currencyObserver = currency -> {
369             setCurrency(currency);
370             adapter.checkTransactionSubmittable();
371         };
372
373         currencyGapObserver =
374                 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
375                         hasGap);
376
377         currencyPositionObserver =
378                 position -> updateCurrencyPositionAndPadding(position, Data.currencyGap.getValue());
379
380         showCurrencyObserver = showCurrency -> {
381             if (showCurrency) {
382                 tvCurrency.setVisibility(View.VISIBLE);
383             }
384             else {
385                 tvCurrency.setVisibility(View.GONE);
386                 item.setCurrency(null);
387             }
388         };
389
390         commentObserver = comment -> {
391             final View focusedView = tvComment.findFocus();
392             tvComment.setTypeface(null,
393                     (focusedView == tvComment) ? Typeface.NORMAL : Typeface.ITALIC);
394             tvComment.setVisibility(
395                     ((focusedView != tvComment) && Misc.isEmptyOrNull(comment)) ? View.INVISIBLE
396                                                                                 : View.VISIBLE);
397         };
398
399         showCommentsObserver = show -> {
400             final View amountLayout = itemView.findViewById(R.id.amount_layout);
401             ConstraintLayout.LayoutParams amountLayoutParams =
402                     (ConstraintLayout.LayoutParams) amountLayout.getLayoutParams();
403             ConstraintLayout.LayoutParams accountParams =
404                     (ConstraintLayout.LayoutParams) tvAccount.getLayoutParams();
405             if (show) {
406                 accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
407                 accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
408
409                 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
410                 amountLayoutParams.topToBottom = tvAccount.getId();
411
412                 commentLayout.setVisibility(View.VISIBLE);
413             }
414             else {
415                 accountParams.endToStart = amountLayout.getId();
416                 accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
417
418                 amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
419                 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
420
421                 commentLayout.setVisibility(View.GONE);
422             }
423
424             tvAccount.setLayoutParams(accountParams);
425             amountLayout.setLayoutParams(amountLayoutParams);
426
427             transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
428         };
429
430         amountValidityObserver = valid -> {
431             tvAmount.setCompoundDrawablesRelativeWithIntrinsicBounds(
432                     valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
433             tvAmount.setMinEms(valid ? 4 : 5);
434         };
435     }
436     private void commentFocusChanged(View layout, TextView textView, boolean hasFocus) {
437         int textColor;
438         if (hasFocus) {
439             textColor = Colors.defaultTextColor;
440             textView.setTypeface(null, Typeface.NORMAL);
441             textView.setHint(R.string.transaction_account_comment_hint);
442         }
443         else {
444             textColor = Colors.defaultTextColorDisabled;
445             textView.setTypeface(null, Typeface.ITALIC);
446             textView.setHint("");
447             if (Misc.isEmptyOrNull(textView.getText())) {
448                 textView.setVisibility(View.INVISIBLE);
449             }
450         }
451         textView.setTextColor(textColor);
452
453     }
454     private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
455         ConstraintLayout.LayoutParams amountLP =
456                 (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
457         ConstraintLayout.LayoutParams currencyLP =
458                 (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
459
460         if (position == Currency.Position.before) {
461             currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
462             currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
463
464             amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
465             amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
466             amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
467             amountLP.startToEnd = tvCurrency.getId();
468
469             tvCurrency.setGravity(Gravity.END);
470         }
471         else {
472             currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
473             currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
474
475             amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
476             amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
477             amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
478             amountLP.endToStart = tvCurrency.getId();
479
480             tvCurrency.setGravity(Gravity.START);
481         }
482
483         amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
484         currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
485
486         tvAmount.setLayoutParams(amountLP);
487         tvCurrency.setLayoutParams(currencyLP);
488
489         // distance between the amount and the currency symbol
490         int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
491
492         if (position == Currency.Position.before) {
493             tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
494         }
495         else {
496             tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
497         }
498     }
499     private void setCurrencyString(String currency) {
500         if ((currency == null) || currency.isEmpty()) {
501             tvCurrency.setText(R.string.currency_symbol);
502             tvCurrency.setTextColor(0x7f000000 + (0x00ffffff & Colors.defaultTextColor));
503         }
504         else {
505             tvCurrency.setText(currency);
506             tvCurrency.setTextColor(Colors.defaultTextColor);
507         }
508     }
509     private void setCurrency(Currency currency) {
510         setCurrencyString((currency == null) ? null : currency.getName());
511     }
512     private void setEditable(Boolean editable) {
513         tvDate.setEnabled(editable);
514         tvDescription.setEnabled(editable);
515         tvAccount.setEnabled(editable);
516         tvAmount.setEnabled(editable);
517     }
518     private void beginUpdates() {
519         if (inUpdate)
520             throw new RuntimeException("Already in update mode");
521         inUpdate = true;
522     }
523     private void endUpdates() {
524         if (!inUpdate)
525             throw new RuntimeException("Not in update mode");
526         inUpdate = false;
527     }
528     /**
529      * syncData()
530      * <p>
531      * Stores the data from the UI elements into the model item
532      * Returns true if there were changes made that suggest transaction has to be
533      * checked for being submittable
534      */
535     private boolean syncData() {
536         if (item == null)
537             return false;
538
539         if (syncingData) {
540             Logger.debug("new-trans", "skipping syncData() loop");
541             return false;
542         }
543
544         syncingData = true;
545
546         try {
547             switch (item.getType()) {
548                 case generalData:
549                     item.setDate(String.valueOf(tvDate.getText()));
550                     item.setDescription(String.valueOf(tvDescription.getText()));
551                     item.setTransactionComment(String.valueOf(tvTransactionComment.getText()));
552                     break;
553                 case transactionRow:
554                     final LedgerTransactionAccount account = item.getAccount();
555                     account.setAccountName(String.valueOf(tvAccount.getText()));
556
557                     item.setComment(String.valueOf(tvComment.getText()));
558
559                     String amount = String.valueOf(tvAmount.getText());
560                     amount = amount.trim();
561
562                     if (amount.isEmpty()) {
563                         account.resetAmount();
564                         item.validateAmount();
565                     }
566                     else {
567                         try {
568                             amount = amount.replace(decimalSeparator, decimalDot);
569                             account.setAmount(Float.parseFloat(amount));
570                             item.validateAmount();
571                         }
572                         catch (NumberFormatException e) {
573                             Logger.debug("new-trans", String.format(
574                                     "assuming amount is not set due to number format exception. " +
575                                     "input was '%s'", amount));
576                             account.invalidateAmount();
577                             item.invalidateAmount();
578                         }
579                         final String curr = String.valueOf(tvCurrency.getText());
580                         if (curr.equals(tvCurrency.getContext()
581                                                   .getResources()
582                                                   .getString(R.string.currency_symbol)) ||
583                             curr.isEmpty())
584                             account.setCurrency(null);
585                         else
586                             account.setCurrency(curr);
587                     }
588
589                     break;
590                 case bottomFiller:
591                     throw new RuntimeException("Should not happen");
592             }
593
594             return true;
595         }
596         finally {
597             syncingData = false;
598         }
599     }
600     private void pickTransactionDate() {
601         DatePickerFragment picker = new DatePickerFragment();
602         picker.setFutureDates(mProfile.getFutureDates());
603         picker.setOnDatePickedListener(this);
604         picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
605                 "datePicker");
606     }
607     /**
608      * setData
609      *
610      * @param item updates the UI elements with the data from the model item
611      */
612     @SuppressLint("DefaultLocale")
613     public void setData(NewTransactionModel.Item item) {
614         beginUpdates();
615         try {
616             if (this.item != null && !this.item.equals(item)) {
617                 this.item.stopObservingDate(dateObserver);
618                 this.item.stopObservingDescription(descriptionObserver);
619                 this.item.stopObservingTransactionComment(transactionCommentObserver);
620                 this.item.stopObservingAmountHint(hintObserver);
621                 this.item.stopObservingEditableFlag(editableObserver);
622                 this.item.getModel()
623                          .stopObservingFocusedItem(focusedAccountObserver);
624                 this.item.getModel()
625                          .stopObservingAccountCount(accountCountObserver);
626                 Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
627                 Data.currencyGap.removeObserver(currencyGapObserver);
628                 Data.locale.removeObserver(localeObserver);
629                 this.item.stopObservingCurrency(currencyObserver);
630                 this.item.getModel().showCurrency.removeObserver(showCurrencyObserver);
631                 this.item.stopObservingComment(commentObserver);
632                 this.item.getModel().showComments.removeObserver(showCommentsObserver);
633                 this.item.stopObservingAmountValidity(amountValidityObserver);
634
635                 this.item = null;
636             }
637
638             switch (item.getType()) {
639                 case generalData:
640                     tvDate.setText(item.getFormattedDate());
641                     tvDescription.setText(item.getDescription());
642                     tvTransactionComment.setText(item.getTransactionComment());
643                     lHead.setVisibility(View.VISIBLE);
644                     lAccount.setVisibility(View.GONE);
645                     lPadding.setVisibility(View.GONE);
646                     setEditable(true);
647                     break;
648                 case transactionRow:
649                     LedgerTransactionAccount acc = item.getAccount();
650                     tvAccount.setText(acc.getAccountName());
651                     tvComment.setText(acc.getComment());
652                     if (acc.isAmountSet()) {
653                         tvAmount.setText(String.format("%1.2f", acc.getAmount()));
654                     }
655                     else {
656                         tvAmount.setText("");
657 //                        tvAmount.setHint(R.string.zero_amount);
658                     }
659                     tvAmount.setHint(item.getAmountHint());
660                     setCurrencyString(acc.getCurrency());
661                     lHead.setVisibility(View.GONE);
662                     lAccount.setVisibility(View.VISIBLE);
663                     lPadding.setVisibility(View.GONE);
664                     setEditable(true);
665                     break;
666                 case bottomFiller:
667                     lHead.setVisibility(View.GONE);
668                     lAccount.setVisibility(View.GONE);
669                     lPadding.setVisibility(View.VISIBLE);
670                     setEditable(false);
671                     break;
672             }
673             if (this.item == null) { // was null or has changed
674                 this.item = item;
675                 final NewTransactionActivity activity =
676                         (NewTransactionActivity) tvDescription.getContext();
677
678                 if (!item.isOfType(ItemType.bottomFiller)) {
679                     item.observeEditableFlag(activity, editableObserver);
680                     item.getModel()
681                         .observeFocusedItem(activity, focusedAccountObserver);
682                     item.getModel()
683                         .observeShowComments(activity, showCommentsObserver);
684                 }
685                 switch (item.getType()) {
686                     case generalData:
687                         item.observeDate(activity, dateObserver);
688                         item.observeDescription(activity, descriptionObserver);
689                         item.observeTransactionComment(activity, transactionCommentObserver);
690                         break;
691                     case transactionRow:
692                         item.observeAmountHint(activity, hintObserver);
693                         Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
694                         Data.currencyGap.observe(activity, currencyGapObserver);
695                         Data.locale.observe(activity, localeObserver);
696                         item.observeCurrency(activity, currencyObserver);
697                         item.getModel().showCurrency.observe(activity, showCurrencyObserver);
698                         item.observeComment(activity, commentObserver);
699                         item.getModel()
700                             .observeAccountCount(activity, accountCountObserver);
701                         item.observeAmountValidity(activity, amountValidityObserver);
702                         break;
703                 }
704             }
705         }
706         finally {
707             endUpdates();
708         }
709     }
710     @Override
711     public void onDatePicked(int year, int month, int day) {
712         final Calendar c = GregorianCalendar.getInstance();
713         c.set(year, month, day);
714         item.setDate(c.getTime());
715         boolean focused = tvDescription.requestFocus();
716         if (focused)
717             Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
718
719     }
720     @Override
721     public void descriptionSelected(String description) {
722         tvAccount.setText(description);
723         tvAmount.requestFocus(View.FOCUS_FORWARD);
724     }
725 }