]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/NewTransactionActivity.java
disable account input during submit
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / NewTransactionActivity.java
1 package net.ktnx.mobileledger;
2
3 import android.annotation.TargetApi;
4 import android.database.Cursor;
5 import android.database.MatrixCursor;
6 import android.database.sqlite.SQLiteDatabase;
7 import android.os.Build;
8 import android.os.Bundle;
9 import android.os.Handler;
10 import android.preference.PreferenceManager;
11 import android.provider.FontsContract;
12 import android.support.design.widget.FloatingActionButton;
13 import android.support.design.widget.Snackbar;
14 import android.support.v4.app.DialogFragment;
15 import android.support.v7.app.AppCompatActivity;
16 import android.support.v7.widget.Toolbar;
17 import android.text.Editable;
18 import android.text.InputType;
19 import android.text.TextWatcher;
20 import android.util.Log;
21 import android.util.TypedValue;
22 import android.view.Menu;
23 import android.view.MenuItem;
24 import android.view.MotionEvent;
25 import android.view.View;
26 import android.widget.AutoCompleteTextView;
27 import android.widget.EditText;
28 import android.widget.FilterQueryProvider;
29 import android.widget.ProgressBar;
30 import android.widget.SimpleCursorAdapter;
31 import android.widget.TableLayout;
32 import android.widget.TableRow;
33 import android.widget.TextView;
34
35 import java.util.Objects;
36
37 /*
38  * TODO: auto-fill of transaction description
39  *       if Android O's implementation won't work, add a custom one
40  * TODO: nicer progress while transaction is submitted
41  * TODO: periodic and manual refresh of available accounts
42  *         (now done forcibly each time the main activity is started)
43  * TODO: latest transactions, maybe with browsing further in the past?
44  * TODO: reports
45  * TODO: get rid of the custom session/cookie and auth code?
46  *         (the last problem with the POST was the missing content-length header)
47  * TODO: app icon
48  * TODO: nicer swiping removal with visual feedback
49  * TODO: activity with current balance
50  * TODO: setup wizard
51  * TODO: update accounts/check settings upon change of backend settings
52  *  */
53
54 public class NewTransactionActivity extends AppCompatActivity implements TaskCallback {
55     private TableLayout table;
56     private FloatingActionButton fab;
57     boolean fab_should_be_visible;
58     private ProgressBar progress;
59     private TextView text_date;
60     private TextView text_descr;
61     private static SaveTransactionTask saver;
62     FloatingActionButton.OnVisibilityChangedListener fab_visibility_changed_listener = new FloatingActionButton.OnVisibilityChangedListener() {
63         @Override
64         public void onShown(FloatingActionButton fab) {
65             Log.d("visuals", "FAB shown");
66             super.onShown(fab);
67             if (!fab_should_be_visible) fab.hide();
68         }
69
70         @Override
71         public void onHidden(FloatingActionButton fab) {
72             Log.d("visuals", "FAB hidden");
73             fab.setImageResource(R.drawable.ic_save_white_24dp);
74             fab.setEnabled(true);
75 //            super.onHidden(fab);
76             if (fab_should_be_visible) fab.show();
77         }
78     };
79
80     private void hide_fab() {
81         hide_fab(false);
82     }
83
84     private void hide_fab(boolean force) {
85         if (!fab_should_be_visible && !force) return;
86
87         fab_should_be_visible = false;
88         fab.hide(fab_visibility_changed_listener);
89     }
90
91     private void show_fab() {
92         show_fab(false);
93     }
94
95     private void show_fab(boolean force) {
96         if (fab_should_be_visible && !force) return;
97
98         fab_should_be_visible = true;
99         fab.show(fab_visibility_changed_listener);
100     }
101
102     @Override
103     protected void onCreate(Bundle savedInstanceState) {
104         super.onCreate(savedInstanceState);
105         setContentView(R.layout.activity_new_transaction);
106         Toolbar toolbar = findViewById(R.id.toolbar);
107         setSupportActionBar(toolbar);
108
109         text_date = findViewById(R.id.new_transaction_date);
110         text_descr = findViewById(R.id.new_transaction_description);
111
112         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
113             text_descr.setAutofillHints("");
114         }
115
116         fab = findViewById(R.id.fab);
117         fab.setOnClickListener(new View.OnClickListener() {
118             @Override
119             public void onClick(View view) {
120                 new_transaction_save_clicked(view);
121             }
122         });
123         progress = findViewById(R.id.save_transaction_progress);
124
125         Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
126         table = findViewById(R.id.new_transaction_accounts_table);
127         for (int i = 0; i < table.getChildCount(); i++) {
128             TableRow row = (TableRow) table.getChildAt(i);
129             TextView acc_name_view = (TextView) row.getChildAt(0);
130             TextView amount_view = (TextView) row.getChildAt(1);
131             hook_swipe_listener(row);
132             hook_autocompletion_adapter(row);
133             hook_text_change_listener(acc_name_view);
134             hook_text_change_listener(amount_view);
135 //            Log.d("swipe", "hooked to row "+i);
136         }
137     }
138
139     public void new_transaction_save_clicked(View view) {
140         fab.setEnabled(false);
141         toggle_all_editing(false);
142         progress.setVisibility(View.VISIBLE);
143
144         saver = new SaveTransactionTask(this);
145
146         saver.setPref(PreferenceManager.getDefaultSharedPreferences(this));
147         LedgerTransaction tr = new LedgerTransaction(text_date.getText().toString(), text_descr.getText().toString());
148
149         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
150         for ( int i = 0; i < table.getChildCount(); i++ ) {
151             TableRow row = (TableRow) table.getChildAt(i);
152             String acc = ((TextView) row.getChildAt(0)).getText().toString();
153             String amt = ((TextView) row.getChildAt(1)).getText().toString();
154             LedgerTransactionItem item =
155                     amt.length() > 0
156                     ? new LedgerTransactionItem( acc, Float.parseFloat(amt))
157                     : new LedgerTransactionItem( acc );
158
159             tr.add_item(item);
160         }
161         saver.execute(tr);
162     }
163
164     private void toggle_all_editing(boolean enabled) {
165         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
166         for (int i = 0; i < table.getChildCount(); i++) {
167             TableRow row = (TableRow) table.getChildAt(i);
168             for (int j = 0; j < row.getChildCount(); j++) {
169                 row.getChildAt(j).setEnabled(enabled);
170             }
171         }
172     }
173
174     private void hook_swipe_listener(final TableRow row) {
175         row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
176             public void onSwipeLeft() {
177 //                Log.d("swipe", "LEFT" + row.getId());
178                 if (table.getChildCount() > 2) {
179                     table.removeView(row);
180 //                    Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
181                 }
182                 else {
183                     Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required, Snackbar.LENGTH_LONG)
184                             .setAction("Action", null).show();
185                 }
186             }
187 //            @Override
188 //            public boolean performClick(View view, MotionEvent m) {
189 //                return true;
190 //            }
191             public boolean onTouch(View view, MotionEvent m) {
192                 return gestureDetector.onTouchEvent(m);
193             }
194         });
195     }
196
197     private void hook_text_change_listener(final TextView view) {
198         view.addTextChangedListener(new TextWatcher() {
199             @Override
200             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
201
202             }
203
204             @Override
205             public void onTextChanged(CharSequence s, int start, int before, int count) {
206
207             }
208
209             @Override
210             public void afterTextChanged(Editable s) {
211 //                Log.d("input", "text changed");
212                 check_transaction_submittable();
213             }
214         });
215
216     }
217
218     @TargetApi(Build.VERSION_CODES.N)
219     private void hook_autocompletion_adapter(final TableRow row) {
220         String[] from = {"name"};
221         int[] to = {android.R.id.text1};
222         SQLiteDatabase db = MobileLedgerDB.db;
223
224         AutoCompleteTextView acc = (AutoCompleteTextView) row.getChildAt(0);
225         SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null, from, to, 0);
226         adapter.setStringConversionColumn(1);
227
228         FilterQueryProvider provider = new FilterQueryProvider() {
229             @Override
230             public Cursor runQuery(CharSequence constraint) {
231                 if (constraint == null) return null;
232
233                 String str = constraint.toString().toUpperCase();
234                 Log.d("autocompletion", "Looking for "+str);
235                 String[] col_names = {FontsContract.Columns._ID, "name"};
236                 MatrixCursor c = new MatrixCursor(col_names);
237
238                 Cursor matches = db.rawQuery("SELECT name FROM accounts WHERE UPPER(name) LIKE '%'||?||'%' ORDER BY name;", new String[]{str});
239
240                 try {
241                     int i = 0;
242                     while (matches.moveToNext()) {
243                         String name = matches.getString(0);
244                         Log.d("autocompletion-match", name);
245                         c.newRow().add(i++).add(name);
246                     }
247                 }
248                 finally {
249                     matches.close();
250                 }
251
252                 return c;
253
254             }
255         };
256
257         adapter.setFilterQueryProvider(provider);
258
259         acc.setAdapter(adapter);
260     }
261
262     public boolean onCreateOptionsMenu(Menu menu) {
263         // Inflate the menu; this adds items to the action bar if it is present.
264         getMenuInflater().inflate(R.menu.new_transaction, menu);
265
266         return true;
267     }
268
269     public void pickTransactionDate(View view) {
270         DialogFragment picker = new DatePickerFragment();
271         picker.show(getSupportFragmentManager(), "datePicker");
272     }
273
274     public int dp2px(float dp) {
275         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
276     }
277
278     private void do_add_account_row(boolean focus) {
279         final AutoCompleteTextView acc = new AutoCompleteTextView(this);
280         acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 9f));
281         acc.setHint(R.string.new_transaction_account_hint);
282         acc.setWidth(0);
283
284         final EditText amt = new EditText(this);
285         amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));
286         amt.setHint(R.string.new_transaction_amount_hint);
287         amt.setWidth(0);
288         amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL );
289         amt.setMinWidth(dp2px(40));
290         amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
291
292         final TableRow row = new TableRow(this);
293         row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
294         row.addView(acc);
295         row.addView(amt);
296         table.addView(row);
297
298         if (focus) acc.requestFocus();
299
300         hook_swipe_listener(row);
301         hook_autocompletion_adapter(row);
302         hook_text_change_listener(acc);
303         hook_text_change_listener(amt);
304     }
305
306     public void addTransactionAccountFromMenu(MenuItem item) {
307         do_add_account_row(true);
308     }
309
310     private void check_transaction_submittable() {
311         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
312         int accounts = 0;
313         int accounts_with_values = 0;
314         int empty_rows = 0;
315         for(int i = 0; i < table.getChildCount(); i++ ) {
316             TableRow row = (TableRow) table.getChildAt(i);
317
318             TextView acc_name_v = (TextView) row.getChildAt(0);
319
320             String acc_name = String.valueOf(acc_name_v.getText());
321             acc_name = acc_name.trim();
322             if (!acc_name.isEmpty()) {
323                 accounts++;
324
325                 TextView amount_v = (TextView) row.getChildAt(1);
326                 String amt = String.valueOf(amount_v.getText());
327
328                 if (!amt.isEmpty()) accounts_with_values++;
329             } else empty_rows++;
330         }
331
332         if (accounts_with_values == accounts && empty_rows == 0) {
333             do_add_account_row(false);
334         }
335
336         if ((accounts >= 2) && (accounts_with_values >= (accounts - 1))) {
337             show_fab();
338         } else hide_fab();
339     }
340
341     @Override
342     public void done() {
343         fab.setImageResource(R.drawable.ic_check_white_24dp);
344         progress.setVisibility(View.INVISIBLE);
345         Log.d("visuals", "hiding progress");
346
347         fab_should_be_visible = false;
348         final Handler fade_out = new Handler();
349         fade_out.postDelayed(new Runnable() {
350             @Override
351             public void run() {
352                 Log.d("visuals", "hiding FAB");
353
354                 hide_fab(true);
355             }
356         }, 1000);
357         reset_form();
358         toggle_all_editing(true);
359     }
360
361     private void reset_form() {
362         text_date.setText("");
363         text_descr.setText("");
364         while(table.getChildCount() > 2) {
365             table.removeViewAt(2);
366         }
367         for( int i = 0; i < 2; i++ ) {
368             TableRow tr = (TableRow) table.getChildAt(i);
369             if ( tr == null) break;
370
371             ((TextView)tr.getChildAt(0)).setText("");
372             ((TextView)tr.getChildAt(1)).setText("");
373         }
374
375         text_descr.requestFocus();
376     }
377 }