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