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