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