]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionActivity.java
new transaction: add a clear button to edited fields
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / NewTransactionActivity.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.database.Cursor;
22 import android.graphics.drawable.Drawable;
23 import android.os.AsyncTask;
24 import android.os.Bundle;
25 import android.text.Editable;
26 import android.text.InputType;
27 import android.text.TextWatcher;
28 import android.util.TypedValue;
29 import android.view.Gravity;
30 import android.view.Menu;
31 import android.view.MenuItem;
32 import android.view.MotionEvent;
33 import android.view.View;
34 import android.view.inputmethod.EditorInfo;
35 import android.widget.AutoCompleteTextView;
36 import android.widget.EditText;
37 import android.widget.ProgressBar;
38 import android.widget.TableLayout;
39 import android.widget.TableRow;
40 import android.widget.TextView;
41 import android.widget.Toast;
42
43 import com.google.android.material.floatingactionbutton.FloatingActionButton;
44 import com.google.android.material.snackbar.BaseTransientBottomBar;
45 import com.google.android.material.snackbar.Snackbar;
46
47 import net.ktnx.mobileledger.App;
48 import net.ktnx.mobileledger.BuildConfig;
49 import net.ktnx.mobileledger.R;
50 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
51 import net.ktnx.mobileledger.async.SendTransactionTask;
52 import net.ktnx.mobileledger.async.TaskCallback;
53 import net.ktnx.mobileledger.model.Data;
54 import net.ktnx.mobileledger.model.LedgerTransaction;
55 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
56 import net.ktnx.mobileledger.model.MobileLedgerProfile;
57 import net.ktnx.mobileledger.ui.DatePickerFragment;
58 import net.ktnx.mobileledger.ui.OnSwipeTouchListener;
59 import net.ktnx.mobileledger.utils.Globals;
60 import net.ktnx.mobileledger.utils.MLDB;
61
62 import java.text.ParseException;
63 import java.util.ArrayList;
64 import java.util.Date;
65 import java.util.Locale;
66 import java.util.Objects;
67
68 import androidx.appcompat.widget.Toolbar;
69 import androidx.fragment.app.DialogFragment;
70
71 import static net.ktnx.mobileledger.utils.Logger.debug;
72
73 /*
74  * TODO: nicer progress while transaction is submitted
75  * TODO: reports
76  * TODO: get rid of the custom session/cookie and auth code?
77  *         (the last problem with the POST was the missing content-length header)
78  *  */
79
80 public class NewTransactionActivity extends ProfileThemedActivity
81         implements TaskCallback, DescriptionSelectedCallback {
82     private static SendTransactionTask saver;
83     private TableLayout table;
84     private ProgressBar progress;
85     private FloatingActionButton fab;
86     private TextView tvDate;
87     private AutoCompleteTextView tvDescription;
88     private static boolean isZero(float f) {
89         return (f < 0.005) && (f > -0.005);
90     }
91     @Override
92     protected void onCreate(Bundle savedInstanceState) {
93         super.onCreate(savedInstanceState);
94
95         setContentView(R.layout.activity_new_transaction);
96         Toolbar toolbar = findViewById(R.id.toolbar);
97         setSupportActionBar(toolbar);
98         toolbar.setSubtitle(mProfile.getName());
99
100         tvDate = findViewById(R.id.new_transaction_date);
101         tvDate.setOnFocusChangeListener((v, hasFocus) -> {
102             if (hasFocus) pickTransactionDate(v);
103         });
104         tvDescription = findViewById(R.id.new_transaction_description);
105         MLDB.hookAutocompletionAdapter(this, tvDescription, MLDB.DESCRIPTION_HISTORY_TABLE,
106                 "description", false, findViewById(R.id.new_transaction_acc_1), this, mProfile);
107         hookTextChangeListener(tvDescription);
108         hookClearClickListener(tvDescription);
109
110         progress = findViewById(R.id.save_transaction_progress);
111         fab = findViewById(R.id.fab);
112         fab.setOnClickListener(v -> saveTransaction());
113
114         Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
115         table = findViewById(R.id.new_transaction_accounts_table);
116
117         while (table.getChildCount() < 2) {
118             doAddAccountRow(false);
119         }
120
121         check_transaction_submittable();
122     }
123     private void hookClearClickListener(AutoCompleteTextView v) {
124         final TextWatcher w = new TextWatcher() {
125             private boolean hasText;
126             private boolean hadText;
127             @Override
128             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
129                 hadText = s.length() > 0;
130             }
131             @Override
132             public void onTextChanged(CharSequence s, int start, int before, int count) {
133
134             }
135             @Override
136             public void afterTextChanged(Editable s) {
137                 hasText = s.length() > 0;
138
139                 if (hadText && !hasText) {
140                     v.setCompoundDrawablesRelative(null, null, null, null);
141                 }
142                 if (!hadText && hasText) {
143                     v.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0,
144                             R.drawable.ic_clear_black_24dp, 0);
145                 }
146             }
147         };
148         View.OnFocusChangeListener prevFocusListener = v.getOnFocusChangeListener();
149         v.setOnFocusChangeListener((v12, hasFocus) -> {
150             if (hasFocus) {
151                 if (((TextView) v12).getText().length() > 0) {
152                     ((TextView) v12).setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0,
153                             R.drawable.ic_clear_black_24dp, 0);
154                 }
155                 ((TextView) v12).addTextChangedListener(w);
156             }
157             else {
158                 ((TextView) v12).removeTextChangedListener(w);
159                 ((TextView) v12).setCompoundDrawables(null, null, null, null);
160             }
161
162             if (prevFocusListener != null) prevFocusListener.onFocusChange(v12, hasFocus);
163         });
164
165         v.setOnTouchListener((v1, event) -> {
166             if (event.getAction() == MotionEvent.ACTION_UP)
167                 if (((TextView) v1).getText().length() > 0) {
168                     boolean clearClicked = false;
169                     final float x = event.getX();
170                     final int vw = v1.getWidth();
171                     // start, top, end, bottom (end == 2)
172                     Drawable dwb = ((TextView) v1).getCompoundDrawablesRelative()[2];
173                     if (dwb != null) {
174                         final int dw = dwb.getBounds().width();
175                         if (v1.getLayoutDirection() == View.LAYOUT_DIRECTION_LTR) {
176                             if ((x > vw - dw)) clearClicked = true;
177                         }
178                         else {
179                             if (x < vw - dw) clearClicked = true;
180                         }
181                         if (clearClicked) {
182                             ((TextView) v1).setText("");
183                             v1.requestFocus();
184                             return true;
185                         }
186                     }
187                 }
188             v.performClick();
189             return false;
190         });
191     }
192     @Override
193     protected void initProfile() {
194         String profileUUID = getIntent().getStringExtra("profile_uuid");
195
196         if (profileUUID != null) {
197             mProfile = Data.getProfile(profileUUID);
198             if (mProfile == null) finish();
199         }
200         else super.initProfile();
201     }
202     @Override
203     public void finish() {
204         super.finish();
205         overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
206     }
207
208     @Override
209     public boolean onOptionsItemSelected(MenuItem item) {
210         switch (item.getItemId()) {
211             case android.R.id.home:
212                 finish();
213                 return true;
214         }
215         return super.onOptionsItemSelected(item);
216     }
217     @Override
218     protected void onStart() {
219         super.onStart();
220         if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
221     }
222     public void saveTransaction() {
223         if (fab != null) fab.setEnabled(false);
224         toggleAllEditing(false);
225         progress.setVisibility(View.VISIBLE);
226         try {
227
228             saver = new SendTransactionTask(this, mProfile);
229
230             String dateString = tvDate.getText().toString();
231             Date date;
232             if (dateString.isEmpty()) date = new Date();
233             else date = Globals.parseLedgerDate(dateString);
234             LedgerTransaction tr = new LedgerTransaction(null, date, tvDescription.getText().toString(), mProfile);
235
236             TableLayout table = findViewById(R.id.new_transaction_accounts_table);
237             LedgerTransactionAccount emptyAmountAccount = null;
238             float emptyAmountAccountBalance = 0;
239             for (int i = 0; i < table.getChildCount(); i++) {
240                 TableRow row = (TableRow) table.getChildAt(i);
241                 String acc = ((TextView) row.getChildAt(0)).getText().toString();
242                 if (acc.isEmpty()) continue;
243
244                 String amt = ((TextView) row.getChildAt(1)).getText().toString();
245                 LedgerTransactionAccount item;
246                 if (amt.length() > 0) {
247                     final float amount = Float.parseFloat(amt);
248                     item = new LedgerTransactionAccount(acc, amount);
249                     emptyAmountAccountBalance += amount;
250                 }
251                 else {
252                     item = new LedgerTransactionAccount(acc);
253                     emptyAmountAccount = item;
254                 }
255
256                 tr.addAccount(item);
257             }
258
259             if (emptyAmountAccount != null)
260                 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
261             saver.execute(tr);
262         }
263         catch (ParseException e) {
264             debug("new-transaction", "Parse error", e);
265             Toast.makeText(this, getResources().getString(R.string.error_invalid_date),
266                     Toast.LENGTH_LONG).show();
267             tvDate.requestFocus();
268
269             progress.setVisibility(View.GONE);
270             toggleAllEditing(true);
271             if (fab != null) fab.setEnabled(true);
272         }
273         catch (Exception e) {
274             debug("new-transaction", "Unknown error", e);
275
276             progress.setVisibility(View.GONE);
277             toggleAllEditing(true);
278             if (fab != null) fab.setEnabled(true);
279         }
280     }
281     private void toggleAllEditing(boolean enabled) {
282         tvDate.setEnabled(enabled);
283         tvDescription.setEnabled(enabled);
284         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
285         for (int i = 0; i < table.getChildCount(); i++) {
286             TableRow row = (TableRow) table.getChildAt(i);
287             for (int j = 0; j < row.getChildCount(); j++) {
288                 row.getChildAt(j).setEnabled(enabled);
289             }
290         }
291     }
292     private void hookSwipeListener(final TableRow row) {
293         row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
294             private void onSwipeAside() {
295                 if (table.getChildCount() > 2) {
296                     TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
297                     TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
298                     TextView prev_amt =
299                             (prev_row != null) ? (TextView) prev_row.getChildAt(1) : tvDescription;
300                     TextView next_acc =
301                             (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
302
303                     if (next_acc == null) {
304                         prev_amt.setNextFocusRightId(R.id.none);
305                         prev_amt.setNextFocusForwardId(R.id.none);
306                         prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
307                     }
308                     else {
309                         prev_amt.setNextFocusRightId(next_acc.getId());
310                         prev_amt.setNextFocusForwardId(next_acc.getId());
311                         prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
312                     }
313
314                     if (row.hasFocus()) {
315                         if (next_acc != null) next_acc.requestFocus();
316                         else prev_amt.requestFocus();
317                     }
318
319                     table.removeView(row);
320                     check_transaction_submittable();
321 //                    Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
322                 }
323                 else {
324                     Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required,
325                             Snackbar.LENGTH_LONG).setAction("Action", null).show();
326                 }
327             }
328             public void onSwipeLeft() {
329                 onSwipeAside();
330             }
331             public void onSwipeRight() {
332                 onSwipeAside();
333             }
334             //            @Override
335 //            public boolean performClick(View view, MotionEvent m) {
336 //                return true;
337 //            }
338             public boolean onTouch(View view, MotionEvent m) {
339                 return gestureDetector.onTouchEvent(m);
340             }
341         });
342     }
343
344     public void simulateCrash(MenuItem item) {
345         debug("crash", "Will crash intentionally");
346         new AsyncCrasher().execute();
347     }
348     public boolean onCreateOptionsMenu(Menu menu) {
349         // Inflate the menu; this adds items to the action bar if it is present.
350         getMenuInflater().inflate(R.menu.new_transaction, menu);
351
352         if (BuildConfig.DEBUG) {
353             menu.findItem(R.id.action_simulate_crash).setVisible(true);
354         }
355         check_transaction_submittable();
356
357         return true;
358     }
359
360     public void pickTransactionDate(View view) {
361         DialogFragment picker = new DatePickerFragment();
362         picker.show(getSupportFragmentManager(), "datePicker");
363     }
364
365     public int dp2px(float dp) {
366         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
367                 getResources().getDisplayMetrics()));
368     }
369     private void hookTextChangeListener(final TextView view) {
370         view.addTextChangedListener(new TextWatcher() {
371             @Override
372             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
373
374             }
375
376             @Override
377             public void onTextChanged(CharSequence s, int start, int before, int count) {
378
379             }
380
381             @Override
382             public void afterTextChanged(Editable s) {
383 //                debug("input", "text changed");
384                 check_transaction_submittable();
385             }
386         });
387
388     }
389     private TableRow doAddAccountRow(boolean focus) {
390         final AutoCompleteTextView acc = new AutoCompleteTextView(this);
391         acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
392                 TableRow.LayoutParams.WRAP_CONTENT, 9f));
393         acc.setHint(R.string.new_transaction_account_hint);
394         acc.setWidth(0);
395         acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
396                           EditorInfo.IME_FLAG_NAVIGATE_NEXT);
397         acc.setSingleLine(true);
398
399         final EditText amt = new EditText(this);
400         amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
401                 TableRow.LayoutParams.MATCH_PARENT, 1f));
402         amt.setHint(R.string.new_transaction_amount_hint);
403         amt.setWidth(0);
404         amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED |
405                          InputType.TYPE_NUMBER_FLAG_DECIMAL);
406         amt.setMinWidth(dp2px(40));
407         amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
408         amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
409         amt.setSelectAllOnFocus(true);
410
411         // forward navigation support
412         TextView last_amt;
413         int rows = table.getChildCount();
414         if (rows > 0) {
415             final TableRow last_row = (TableRow) table.getChildAt(rows - 1);
416             last_amt = (TextView) last_row.getChildAt(1);
417         }
418         else {
419             last_amt = tvDescription;
420         }
421         last_amt.setNextFocusForwardId(acc.getId());
422         last_amt.setNextFocusRightId(acc.getId());
423         last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
424         acc.setNextFocusForwardId(amt.getId());
425         acc.setNextFocusRightId(amt.getId());
426
427         final TableRow row = new TableRow(this);
428         row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
429                 TableRow.LayoutParams.MATCH_PARENT));
430         row.setGravity(Gravity.BOTTOM);
431         row.addView(acc);
432         row.addView(amt);
433         table.addView(row);
434
435         if (focus) acc.requestFocus();
436
437         hookSwipeListener(row);
438         MLDB.hookAutocompletionAdapter(this, acc, MLDB.ACCOUNTS_TABLE, "name", true, amt, null,
439                 mProfile);
440         hookTextChangeListener(acc);
441         hookClearClickListener(acc);
442         hookTextChangeListener(amt);
443
444         return row;
445     }
446     public void addTransactionAccountFromMenu(MenuItem item) {
447         doAddAccountRow(true);
448     }
449     public void resetTransactionFromMenu(MenuItem item) {
450         resetForm();
451     }
452     public void saveTransactionFromMenu(MenuItem item) {
453         saveTransaction();
454     }
455     // rules:
456     // 1) at least two account names
457     // 2) each amount must have account name
458     // 3) amounts must balance to 0, or
459     // 3a) there must be exactly one empty amount
460     // 4) empty accounts with empty amounts are ignored
461     // 5) a row with an empty account name or empty amount is guaranteed to exist
462     @SuppressLint("DefaultLocale")
463     private void check_transaction_submittable() {
464         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
465         int accounts = 0;
466         int accounts_with_values = 0;
467         int amounts = 0;
468         int amounts_with_accounts = 0;
469         int empty_rows = 0;
470         TextView empty_amount = null;
471         boolean single_empty_amount = false;
472         boolean single_empty_amount_has_account = false;
473         float running_total = 0f;
474         boolean have_description =
475                 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
476                         .isEmpty();
477
478         try {
479             for (int i = 0; i < table.getChildCount(); i++) {
480                 TableRow row = (TableRow) table.getChildAt(i);
481
482                 TextView acc_name_v = (TextView) row.getChildAt(0);
483                 TextView amount_v = (TextView) row.getChildAt(1);
484                 String amt = String.valueOf(amount_v.getText());
485                 String acc_name = String.valueOf(acc_name_v.getText());
486                 acc_name = acc_name.trim();
487
488                 if (!acc_name.isEmpty()) {
489                     accounts++;
490
491                     if (!amt.isEmpty()) {
492                         accounts_with_values++;
493                     }
494                 }
495                 else empty_rows++;
496
497                 if (amt.isEmpty()) {
498                     amount_v.setHint(String.format("%1.2f", 0f));
499                     if (empty_amount == null) {
500                         empty_amount = amount_v;
501                         single_empty_amount = true;
502                         single_empty_amount_has_account = !acc_name.isEmpty();
503                     }
504                     else if (!acc_name.isEmpty()) single_empty_amount = false;
505                 }
506                 else {
507                     amounts++;
508                     if (!acc_name.isEmpty()) amounts_with_accounts++;
509                     running_total += Float.valueOf(amt);
510                 }
511             }
512
513             if ((empty_rows == 0) &&
514                 ((table.getChildCount() == accounts) || (table.getChildCount() == amounts)))
515             {
516                 doAddAccountRow(false);
517             }
518
519             debug("submittable", String.format("accounts=%d, accounts_with_values=%s, " +
520                                                "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
521                                                "single_empty_with_acc=%s", accounts,
522                     accounts_with_values, amounts_with_accounts, amounts, running_total,
523                     (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
524
525             if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
526                 (amounts_with_accounts == amounts) &&
527                 (single_empty_amount && single_empty_amount_has_account || isZero(running_total)))
528             {
529                 if (fab != null) {
530                     fab.show();
531                     fab.setEnabled(true);
532                 }
533             }
534             else {
535                 if (fab != null) fab.hide();
536             }
537
538             if (single_empty_amount) {
539                 empty_amount.setHint(String.format("%1.2f",
540                         (Math.abs(running_total) > 0.005) ? -running_total : 0f));
541             }
542
543         }
544         catch (NumberFormatException e) {
545             if (fab != null) fab.hide();
546         }
547         catch (Exception e) {
548             e.printStackTrace();
549             if (fab != null) fab.hide();
550         }
551     }
552
553     @Override
554     public void done(String error) {
555         progress.setVisibility(View.INVISIBLE);
556         debug("visuals", "hiding progress");
557
558         if (error == null) resetForm();
559         else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
560                 BaseTransientBottomBar.LENGTH_LONG).show();
561
562         toggleAllEditing(true);
563         check_transaction_submittable();
564     }
565
566     private void resetForm() {
567         tvDate.setText("");
568         tvDescription.setText("");
569
570         tvDescription.requestFocus();
571
572         while (table.getChildCount() > 2) {
573             table.removeViewAt(2);
574         }
575         for (int i = 0; i < 2; i++) {
576             TableRow tr = (TableRow) table.getChildAt(i);
577             if (tr == null) break;
578
579             ((TextView) tr.getChildAt(0)).setText("");
580             ((TextView) tr.getChildAt(1)).setText("");
581         }
582     }
583     @Override
584     public void descriptionSelected(String description) {
585         debug("descr selected", description);
586         if (!inputStateIsInitial()) return;
587
588         String accFilter = mProfile.getPreferredAccountsFilter();
589
590         ArrayList<String> params = new ArrayList<>();
591         StringBuilder sb = new StringBuilder(
592                 "select t.profile, t.id from transactions t where t.description=?");
593         params.add(description);
594
595         if (accFilter != null) {
596             sb.append(" AND EXISTS (").append("SELECT 1 FROM transaction_accounts ta ")
597                     .append("WHERE ta.profile = t.profile").append(" AND ta.transaction_id = t.id")
598                     .append(" AND UPPER(ta.account_name) LIKE '%'||?||'%')");
599             params.add(accFilter.toUpperCase());
600         }
601
602         sb.append(" ORDER BY date desc limit 1");
603
604         final String sql = sb.toString();
605         debug("descr", sql);
606         debug("descr", params.toString());
607
608         try (Cursor c = App.getDatabase().rawQuery(sql, params.toArray(new String[]{}))) {
609             if (!c.moveToNext()) return;
610
611             String profileUUID = c.getString(0);
612             int transactionId = c.getInt(1);
613             LedgerTransaction tr;
614             MobileLedgerProfile profile = Data.getProfile(profileUUID);
615             if (profile == null) throw new RuntimeException(String.format(
616                     "Unable to find profile %s, which is supposed to contain " +
617                     "transaction %d with description %s", profileUUID, transactionId, description));
618
619             tr = profile.loadTransaction(transactionId);
620             ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
621             TableRow firstNegative = null;
622             int negativeCount = 0;
623             for (int i = 0; i < accounts.size(); i++) {
624                 LedgerTransactionAccount acc = accounts.get(i);
625                 TableRow row = (TableRow) table.getChildAt(i);
626                 if (row == null) row = doAddAccountRow(false);
627
628                 ((TextView) row.getChildAt(0)).setText(acc.getAccountName());
629                 ((TextView) row.getChildAt(1))
630                         .setText(String.format(Locale.US, "%1.2f", acc.getAmount()));
631
632                 if (acc.getAmount() < 0.005) {
633                     if (firstNegative == null) firstNegative = row;
634                     negativeCount++;
635                 }
636             }
637
638             if (negativeCount == 1) {
639                 ((TextView) firstNegative.getChildAt(1)).setText(null);
640             }
641
642             check_transaction_submittable();
643
644             EditText firstAmount = (EditText) ((TableRow) table.getChildAt(0)).getChildAt(1);
645             String amtString = String.valueOf(firstAmount.getText());
646             firstAmount.requestFocus();
647             firstAmount.setSelection(0, amtString.length());
648         }
649
650     }
651     private boolean inputStateIsInitial() {
652         table = findViewById(R.id.new_transaction_accounts_table);
653
654         if (table.getChildCount() != 2) return false;
655
656         for (int i = 0; i < 2; i++) {
657             TableRow row = (TableRow) table.getChildAt(i);
658             if (((TextView) row.getChildAt(0)).getText().length() > 0) return false;
659             if (((TextView) row.getChildAt(1)).getText().length() > 0) return false;
660         }
661
662         return true;
663     }
664     private class AsyncCrasher extends AsyncTask<Void, Void, Void> {
665         @Override
666         protected Void doInBackground(Void... voids) {
667             throw new RuntimeException("Simulated crash");
668         }
669     }
670 }