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