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