]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionItemHolder.java
posting-level flag for amount validity; drop custom amount text filter
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / NewTransactionItemHolder.java
1 /*
2  * Copyright © 2019 Damyan Ivanov.
3  * This file is part of MoLe.
4  * MoLe is free software: you can distribute it and/or modify it
5  * under the term of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your opinion), any later version.
8  *
9  * MoLe is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License terms for details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.ui.activity;
19
20 import android.annotation.SuppressLint;
21 import android.graphics.Typeface;
22 import android.os.Build;
23 import android.text.Editable;
24 import android.text.TextWatcher;
25 import android.text.method.DigitsKeyListener;
26 import android.view.Gravity;
27 import android.view.View;
28 import android.view.ViewGroup;
29 import android.view.inputmethod.EditorInfo;
30 import android.widget.AutoCompleteTextView;
31 import android.widget.EditText;
32 import android.widget.FrameLayout;
33 import android.widget.TextView;
34
35 import androidx.annotation.NonNull;
36 import androidx.appcompat.app.AppCompatActivity;
37 import androidx.constraintlayout.widget.ConstraintLayout;
38 import androidx.lifecycle.Observer;
39 import androidx.recyclerview.widget.RecyclerView;
40
41 import net.ktnx.mobileledger.R;
42 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
43 import net.ktnx.mobileledger.model.Currency;
44 import net.ktnx.mobileledger.model.Data;
45 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
46 import net.ktnx.mobileledger.model.MobileLedgerProfile;
47 import net.ktnx.mobileledger.ui.CurrencySelectorFragment;
48 import net.ktnx.mobileledger.ui.DatePickerFragment;
49 import net.ktnx.mobileledger.ui.TextViewClearHelper;
50 import net.ktnx.mobileledger.utils.Colors;
51 import net.ktnx.mobileledger.utils.DimensionUtils;
52 import net.ktnx.mobileledger.utils.Logger;
53 import net.ktnx.mobileledger.utils.MLDB;
54 import net.ktnx.mobileledger.utils.Misc;
55
56 import java.text.DecimalFormatSymbols;
57 import java.util.Calendar;
58 import java.util.Date;
59 import java.util.GregorianCalendar;
60 import java.util.Locale;
61
62 import static net.ktnx.mobileledger.ui.activity.NewTransactionModel.ItemType;
63
64 class NewTransactionItemHolder extends RecyclerView.ViewHolder
65         implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback {
66     private final String decimalSeparator;
67     private final String decimalDot;
68     private final TextView tvCurrency;
69     private final Observer<Boolean> showCommentsObserver;
70     private final TextView tvTransactionComment;
71     private NewTransactionModel.Item item;
72     private TextView tvDate;
73     private AutoCompleteTextView tvDescription;
74     private AutoCompleteTextView tvAccount;
75     private TextView tvComment;
76     private EditText tvAmount;
77     private ViewGroup lHead;
78     private ViewGroup lAccount;
79     private FrameLayout lPadding;
80     private MobileLedgerProfile mProfile;
81     private Date date;
82     private Observer<Date> dateObserver;
83     private Observer<String> descriptionObserver;
84     private Observer<String> transactionCommentObserver;
85     private Observer<String> hintObserver;
86     private Observer<Integer> focusedAccountObserver;
87     private Observer<Integer> accountCountObserver;
88     private Observer<Boolean> editableObserver;
89     private Observer<Currency.Position> currencyPositionObserver;
90     private Observer<Boolean> currencyGapObserver;
91     private Observer<Locale> localeObserver;
92     private Observer<Currency> currencyObserver;
93     private Observer<Boolean> showCurrencyObserver;
94     private Observer<String> commentObserver;
95     private Observer<Boolean> amountValidityObserver;
96     private boolean inUpdate = false;
97     private boolean syncingData = false;
98     private View commentButton;
99     //TODO multiple amounts with different currencies per posting
100     NewTransactionItemHolder(@NonNull View itemView, NewTransactionItemsAdapter adapter) {
101         super(itemView);
102         lAccount = itemView.findViewById(R.id.ntr_account);
103         tvAccount = lAccount.findViewById(R.id.account_row_acc_name);
104         tvComment = lAccount.findViewById(R.id.comment);
105         tvTransactionComment = itemView.findViewById(R.id.transaction_comment);
106         new TextViewClearHelper().attachToTextView((EditText) tvComment);
107         commentButton = lAccount.findViewById(R.id.comment_button);
108         tvAmount = itemView.findViewById(R.id.account_row_acc_amounts);
109         tvCurrency = itemView.findViewById(R.id.currency);
110         tvDate = itemView.findViewById(R.id.new_transaction_date);
111         tvDescription = itemView.findViewById(R.id.new_transaction_description);
112         lHead = itemView.findViewById(R.id.ntr_data);
113         lPadding = itemView.findViewById(R.id.ntr_padding);
114         final View commentLayout = itemView.findViewById(R.id.comment_layout);
115         final View transactionCommentLayout =
116                 itemView.findViewById(R.id.transaction_comment_layout);
117
118         tvDescription.setNextFocusForwardId(View.NO_ID);
119         tvAccount.setNextFocusForwardId(View.NO_ID);
120         tvAmount.setNextFocusForwardId(View.NO_ID); // magic!
121
122         tvDate.setOnClickListener(v -> pickTransactionDate());
123
124         commentButton.setOnClickListener(v -> {
125             tvComment.setVisibility(View.VISIBLE);
126             tvComment.requestFocus();
127         });
128
129         transactionCommentLayout.findViewById(R.id.comment_button)
130                                 .setOnClickListener(v -> {
131                                     tvTransactionComment.setVisibility(View.VISIBLE);
132                                     tvTransactionComment.requestFocus();
133                                 });
134
135         mProfile = Data.profile.getValue();
136         if (mProfile == null)
137             throw new AssertionError();
138
139         View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
140             final int id = v.getId();
141             if (hasFocus) {
142                 boolean wasSyncing = syncingData;
143                 syncingData = true;
144                 try {
145                     final int pos = getAdapterPosition();
146                     adapter.updateFocusedItem(pos);
147                     switch (id) {
148                         case R.id.account_row_acc_name:
149                             adapter.noteFocusIsOnAccount(pos);
150                             break;
151                         case R.id.account_row_acc_amounts:
152                             adapter.noteFocusIsOnAmount(pos);
153                             break;
154                         case R.id.comment:
155                             adapter.noteFocusIsOnComment(pos);
156                             break;
157                         case R.id.transaction_comment:
158                             adapter.noteFocusIsOnTransactionComment(pos);
159                             break;
160                         case R.id.new_transaction_description:
161                             adapter.noteFocusIsOnDescription(pos);
162                             break;
163                     }
164                 }
165                 finally {
166                     syncingData = wasSyncing;
167                 }
168             }
169
170             if (id == R.id.comment) {
171                 commentFocusChanged(commentLayout, tvComment, hasFocus);
172             }
173             else if (id == R.id.transaction_comment) {
174                 commentFocusChanged(transactionCommentLayout, tvTransactionComment, hasFocus);
175             }
176         };
177
178         tvDescription.setOnFocusChangeListener(focusMonitor);
179         tvAccount.setOnFocusChangeListener(focusMonitor);
180         tvAmount.setOnFocusChangeListener(focusMonitor);
181         tvComment.setOnFocusChangeListener(focusMonitor);
182         tvTransactionComment.setOnFocusChangeListener(focusMonitor);
183
184         MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
185                 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
186         MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
187                 "name", true, this, mProfile);
188
189         // FIXME: react on configuration (locale) changes
190         decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
191                                                               .getMonetaryDecimalSeparator());
192         decimalDot = ".";
193
194         final TextWatcher tw = new TextWatcher() {
195             @Override
196             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
197             }
198
199             @Override
200             public void onTextChanged(CharSequence s, int start, int before, int count) {
201             }
202
203             @Override
204             public void afterTextChanged(Editable s) {
205 //                debug("input", "text changed");
206                 if (inUpdate)
207                     return;
208
209                 Logger.debug("textWatcher", "calling syncData()");
210                 syncData();
211                 Logger.debug("textWatcher",
212                         "syncData() returned, checking if transaction is submittable");
213                 adapter.checkTransactionSubmittable();
214                 Logger.debug("textWatcher", "done");
215             }
216         };
217         final TextWatcher amountWatcher = new TextWatcher() {
218             @Override
219             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
220                 Logger.debug("num",
221                         String.format(Locale.US, "beforeTextChanged: start=%d, count=%d, after=%d",
222                                 start, count, after));
223             }
224             @Override
225             public void onTextChanged(CharSequence s, int start, int before, int count) {}
226             @Override
227             public void afterTextChanged(Editable s) {
228
229                 if (syncData())
230                     adapter.checkTransactionSubmittable();
231             }
232         };
233         tvDescription.addTextChangedListener(tw);
234         tvTransactionComment.addTextChangedListener(tw);
235         tvAccount.addTextChangedListener(tw);
236         tvComment.addTextChangedListener(tw);
237         tvAmount.addTextChangedListener(amountWatcher);
238
239         tvCurrency.setOnClickListener(v -> {
240             CurrencySelectorFragment cpf = new CurrencySelectorFragment();
241             cpf.showPositionAndPadding();
242             cpf.setOnCurrencySelectedListener(c -> item.setCurrency(c));
243             final AppCompatActivity activity = (AppCompatActivity) v.getContext();
244             cpf.show(activity.getSupportFragmentManager(), "currency-selector");
245         });
246
247         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
248             tvAmount.setKeyListener(
249                     DigitsKeyListener.getInstance(Data.locale.getValue(), true, true));
250         else
251             tvAmount.setKeyListener(
252                     DigitsKeyListener.getInstance("0123456789+-" + decimalSeparator + decimalDot));
253
254         dateObserver = date -> {
255             if (syncingData)
256                 return;
257             syncingData = true;
258             try {
259                 tvDate.setText(item.getFormattedDate());
260             }
261             finally {
262                 syncingData = false;
263             }
264         };
265         descriptionObserver = description -> {
266             if (syncingData)
267                 return;
268             syncingData = true;
269             try {
270                 tvDescription.setText(description);
271             }
272             finally {
273                 syncingData = false;
274             }
275         };
276         transactionCommentObserver = transactionComment -> {
277             final View focusedView = tvTransactionComment.findFocus();
278             tvTransactionComment.setTypeface(null,
279                     (focusedView == tvTransactionComment) ? Typeface.NORMAL : Typeface.ITALIC);
280             tvTransactionComment.setVisibility(((focusedView != tvTransactionComment) &&
281                                                 Misc.isEmptyOrNull(transactionComment))
282                                                ? View.INVISIBLE : View.VISIBLE);
283
284         };
285         hintObserver = hint -> {
286             if (syncingData)
287                 return;
288             syncingData = true;
289             try {
290                 if (hint == null)
291                     tvAmount.setHint(R.string.zero_amount);
292                 else
293                     tvAmount.setHint(hint);
294             }
295             finally {
296                 syncingData = false;
297             }
298         };
299         editableObserver = this::setEditable;
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         localeObserver = locale -> {
371             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
372                 tvAmount.setKeyListener(DigitsKeyListener.getInstance(locale, true, true));
373         };
374
375         currencyObserver = currency -> {
376             setCurrency(currency);
377             adapter.checkTransactionSubmittable();
378         };
379
380         currencyGapObserver =
381                 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
382                         hasGap);
383
384         currencyPositionObserver =
385                 position -> updateCurrencyPositionAndPadding(position, Data.currencyGap.getValue());
386
387         showCurrencyObserver = showCurrency -> {
388             if (showCurrency) {
389                 tvCurrency.setVisibility(View.VISIBLE);
390             }
391             else {
392                 tvCurrency.setVisibility(View.GONE);
393                 item.setCurrency(null);
394             }
395         };
396
397         commentObserver = comment -> {
398             final View focusedView = tvComment.findFocus();
399             tvComment.setTypeface(null,
400                     (focusedView == tvComment) ? Typeface.NORMAL : Typeface.ITALIC);
401             tvComment.setVisibility(
402                     ((focusedView != tvComment) && Misc.isEmptyOrNull(comment)) ? View.INVISIBLE
403                                                                                 : View.VISIBLE);
404         };
405
406         showCommentsObserver = show -> {
407             final View amountLayout = itemView.findViewById(R.id.amount_layout);
408             ConstraintLayout.LayoutParams amountLayoutParams =
409                     (ConstraintLayout.LayoutParams) amountLayout.getLayoutParams();
410             ConstraintLayout.LayoutParams accountParams =
411                     (ConstraintLayout.LayoutParams) tvAccount.getLayoutParams();
412             if (show) {
413                 accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
414                 accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
415
416                 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
417                 amountLayoutParams.topToBottom = tvAccount.getId();
418
419                 commentLayout.setVisibility(View.VISIBLE);
420             }
421             else {
422                 accountParams.endToStart = amountLayout.getId();
423                 accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
424
425                 amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
426                 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
427
428                 commentLayout.setVisibility(View.GONE);
429             }
430
431             tvAccount.setLayoutParams(accountParams);
432             amountLayout.setLayoutParams(amountLayoutParams);
433
434             transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
435         };
436
437         amountValidityObserver = valid -> {
438             tvAmount.setCompoundDrawablesRelativeWithIntrinsicBounds(
439                     valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
440             tvAmount.setMinEms(valid ? 4 : 5);
441         };
442     }
443     private void commentFocusChanged(View layout, TextView textView, boolean hasFocus) {
444         int textColor;
445         if (hasFocus) {
446             textColor = Colors.defaultTextColor;
447             textView.setTypeface(null, Typeface.NORMAL);
448             textView.setHint(R.string.transaction_account_comment_hint);
449         }
450         else {
451             textColor = Colors.defaultTextColorDisabled;
452             textView.setTypeface(null, Typeface.ITALIC);
453             textView.setHint("");
454             if (Misc.isEmptyOrNull(textView.getText())) {
455                 textView.setVisibility(View.INVISIBLE);
456             }
457         }
458         textView.setTextColor(textColor);
459
460     }
461     private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
462         ConstraintLayout.LayoutParams amountLP =
463                 (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
464         ConstraintLayout.LayoutParams currencyLP =
465                 (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
466
467         if (position == Currency.Position.before) {
468             currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
469             currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
470
471             amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
472             amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
473             amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
474             amountLP.startToEnd = tvCurrency.getId();
475
476             tvCurrency.setGravity(Gravity.END);
477         }
478         else {
479             currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
480             currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
481
482             amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
483             amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
484             amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
485             amountLP.endToStart = tvCurrency.getId();
486
487             tvCurrency.setGravity(Gravity.START);
488         }
489
490         amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
491         currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
492
493         tvAmount.setLayoutParams(amountLP);
494         tvCurrency.setLayoutParams(currencyLP);
495
496         // distance between the amount and the currency symbol
497         int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
498
499         if (position == Currency.Position.before) {
500             tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
501         }
502         else {
503             tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
504         }
505     }
506     private void setCurrencyString(String currency) {
507         if ((currency == null) || currency.isEmpty()) {
508             tvCurrency.setText(R.string.currency_symbol);
509             tvCurrency.setTextColor(0x7f000000 + (0x00ffffff & Colors.defaultTextColor));
510         }
511         else {
512             tvCurrency.setText(currency);
513             tvCurrency.setTextColor(Colors.defaultTextColor);
514         }
515     }
516     private void setCurrency(Currency currency) {
517         setCurrencyString((currency == null) ? null : currency.getName());
518     }
519     private void setEditable(Boolean editable) {
520         tvDate.setEnabled(editable);
521         tvDescription.setEnabled(editable);
522         tvAccount.setEnabled(editable);
523         tvAmount.setEnabled(editable);
524     }
525     private void beginUpdates() {
526         if (inUpdate)
527             throw new RuntimeException("Already in update mode");
528         inUpdate = true;
529     }
530     private void endUpdates() {
531         if (!inUpdate)
532             throw new RuntimeException("Not in update mode");
533         inUpdate = false;
534     }
535     /**
536      * syncData()
537      * <p>
538      * Stores the data from the UI elements into the model item
539      * Returns true if there were changes made that suggest transaction has to be
540      * checked for being submittable
541      */
542     private boolean syncData() {
543         if (item == null)
544             return false;
545
546         if (syncingData) {
547             Logger.debug("new-trans", "skipping syncData() loop");
548             return false;
549         }
550
551         syncingData = true;
552
553         try {
554             switch (item.getType()) {
555                 case generalData:
556                     item.setDate(String.valueOf(tvDate.getText()));
557                     item.setDescription(String.valueOf(tvDescription.getText()));
558                     item.setTransactionComment(String.valueOf(tvTransactionComment.getText()));
559                     break;
560                 case transactionRow:
561                     final LedgerTransactionAccount account = item.getAccount();
562                     account.setAccountName(String.valueOf(tvAccount.getText()));
563
564                     item.setComment(String.valueOf(tvComment.getText()));
565
566                     String amount = String.valueOf(tvAmount.getText());
567                     amount = amount.trim();
568
569                     if (amount.isEmpty()) {
570                         account.resetAmount();
571                         item.validateAmount();
572                     }
573                     else {
574                         try {
575                             amount = amount.replace(decimalSeparator, decimalDot);
576                             account.setAmount(Float.parseFloat(amount));
577                             item.validateAmount();
578                         }
579                         catch (NumberFormatException e) {
580                             Logger.debug("new-trans", String.format(
581                                     "assuming amount is not set due to number format exception. " +
582                                     "input was '%s'", amount));
583                             account.invalidateAmount();
584                             item.invalidateAmount();
585                         }
586                         final String curr = String.valueOf(tvCurrency.getText());
587                         if (curr.equals(tvCurrency.getContext()
588                                                   .getResources()
589                                                   .getString(R.string.currency_symbol)) ||
590                             curr.isEmpty())
591                             account.setCurrency(null);
592                         else
593                             account.setCurrency(curr);
594                     }
595
596                     break;
597                 case bottomFiller:
598                     throw new RuntimeException("Should not happen");
599             }
600
601             return true;
602         }
603         finally {
604             syncingData = false;
605         }
606     }
607     private void pickTransactionDate() {
608         DatePickerFragment picker = new DatePickerFragment();
609         picker.setFutureDates(mProfile.getFutureDates());
610         picker.setOnDatePickedListener(this);
611         picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
612                 "datePicker");
613     }
614     /**
615      * setData
616      *
617      * @param item updates the UI elements with the data from the model item
618      */
619     @SuppressLint("DefaultLocale")
620     public void setData(NewTransactionModel.Item item) {
621         beginUpdates();
622         try {
623             if (this.item != null && !this.item.equals(item)) {
624                 this.item.stopObservingDate(dateObserver);
625                 this.item.stopObservingDescription(descriptionObserver);
626                 this.item.stopObservingTransactionComment(transactionCommentObserver);
627                 this.item.stopObservingAmountHint(hintObserver);
628                 this.item.stopObservingEditableFlag(editableObserver);
629                 this.item.getModel()
630                          .stopObservingFocusedItem(focusedAccountObserver);
631                 this.item.getModel()
632                          .stopObservingAccountCount(accountCountObserver);
633                 Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
634                 Data.currencyGap.removeObserver(currencyGapObserver);
635                 Data.locale.removeObserver(localeObserver);
636                 this.item.stopObservingCurrency(currencyObserver);
637                 this.item.getModel().showCurrency.removeObserver(showCurrencyObserver);
638                 this.item.stopObservingComment(commentObserver);
639                 this.item.getModel().showComments.removeObserver(showCommentsObserver);
640                 this.item.stopObservingAmountValidity(amountValidityObserver);
641
642                 this.item = null;
643             }
644
645             switch (item.getType()) {
646                 case generalData:
647                     tvDate.setText(item.getFormattedDate());
648                     tvDescription.setText(item.getDescription());
649                     tvTransactionComment.setText(item.getTransactionComment());
650                     lHead.setVisibility(View.VISIBLE);
651                     lAccount.setVisibility(View.GONE);
652                     lPadding.setVisibility(View.GONE);
653                     setEditable(true);
654                     break;
655                 case transactionRow:
656                     LedgerTransactionAccount acc = item.getAccount();
657                     tvAccount.setText(acc.getAccountName());
658                     tvComment.setText(acc.getComment());
659                     if (acc.isAmountSet()) {
660                         tvAmount.setText(String.format("%1.2f", acc.getAmount()));
661                     }
662                     else {
663                         tvAmount.setText("");
664 //                        tvAmount.setHint(R.string.zero_amount);
665                     }
666                     tvAmount.setHint(item.getAmountHint());
667                     setCurrencyString(acc.getCurrency());
668                     lHead.setVisibility(View.GONE);
669                     lAccount.setVisibility(View.VISIBLE);
670                     lPadding.setVisibility(View.GONE);
671                     setEditable(true);
672                     break;
673                 case bottomFiller:
674                     lHead.setVisibility(View.GONE);
675                     lAccount.setVisibility(View.GONE);
676                     lPadding.setVisibility(View.VISIBLE);
677                     setEditable(false);
678                     break;
679             }
680             if (this.item == null) { // was null or has changed
681                 this.item = item;
682                 final NewTransactionActivity activity =
683                         (NewTransactionActivity) tvDescription.getContext();
684
685                 if (!item.isOfType(ItemType.bottomFiller)) {
686                     item.observeEditableFlag(activity, editableObserver);
687                     item.getModel()
688                         .observeFocusedItem(activity, focusedAccountObserver);
689                     item.getModel()
690                         .observeShowComments(activity, showCommentsObserver);
691                 }
692                 switch (item.getType()) {
693                     case generalData:
694                         item.observeDate(activity, dateObserver);
695                         item.observeDescription(activity, descriptionObserver);
696                         item.observeTransactionComment(activity, transactionCommentObserver);
697                         break;
698                     case transactionRow:
699                         item.observeAmountHint(activity, hintObserver);
700                         Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
701                         Data.currencyGap.observe(activity, currencyGapObserver);
702                         Data.locale.observe(activity, localeObserver);
703                         item.observeCurrency(activity, currencyObserver);
704                         item.getModel().showCurrency.observe(activity, showCurrencyObserver);
705                         item.observeComment(activity, commentObserver);
706                         item.getModel()
707                             .observeAccountCount(activity, accountCountObserver);
708                         item.observeAmountValidity(activity, amountValidityObserver);
709                         break;
710                 }
711             }
712         }
713         finally {
714             endUpdates();
715         }
716     }
717     @Override
718     public void onDatePicked(int year, int month, int day) {
719         final Calendar c = GregorianCalendar.getInstance();
720         c.set(year, month, day);
721         item.setDate(c.getTime());
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 }