]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/NewTransactionActivity.java
use clip-art check icon, and show it as soon as the submit completes
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / NewTransactionActivity.java
1 package net.ktnx.mobileledger;
2
3 import android.animation.AnimatorInflater;
4 import android.animation.AnimatorSet;
5 import android.annotation.TargetApi;
6 import android.database.Cursor;
7 import android.database.MatrixCursor;
8 import android.database.sqlite.SQLiteDatabase;
9 import android.os.Build;
10 import android.os.Bundle;
11 import android.os.Handler;
12 import android.preference.PreferenceManager;
13 import android.provider.FontsContract;
14 import android.support.design.widget.FloatingActionButton;
15 import android.support.design.widget.Snackbar;
16 import android.support.v4.app.DialogFragment;
17 import android.support.v7.app.AppCompatActivity;
18 import android.support.v7.widget.Toolbar;
19 import android.text.InputType;
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     private ProgressBar progress;
58     private TextView text_date;
59     private TextView text_descr;
60     private static SaveTransactionTask saver;
61
62     @Override
63     protected void onCreate(Bundle savedInstanceState) {
64         super.onCreate(savedInstanceState);
65         setContentView(R.layout.activity_new_transaction);
66         Toolbar toolbar = findViewById(R.id.toolbar);
67         setSupportActionBar(toolbar);
68
69         text_date = findViewById(R.id.new_transaction_date);
70         text_descr = findViewById(R.id.new_transaction_description);
71
72         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
73             text_descr.setAutofillHints("");
74         }
75
76         fab = findViewById(R.id.fab);
77         fab.setOnClickListener(new View.OnClickListener() {
78             @Override
79             public void onClick(View view) {
80                 new_transaction_save_clicked(view);
81             }
82         });
83         progress = findViewById(R.id.save_transaction_progress);
84
85         Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
86         table = findViewById(R.id.new_transaction_accounts_table);
87         for (int i = 0; i < table.getChildCount(); i++) {
88             hook_swipe_listener((TableRow)table.getChildAt(i));
89             hook_autocompletion_adapter((TableRow)table.getChildAt(i));
90 //            Log.d("swipe", "hooked to row "+i);
91         }
92     }
93
94     public void new_transaction_save_clicked(View view) {
95         fab.setEnabled(false);
96         progress.setVisibility(View.VISIBLE);
97
98         saver = new SaveTransactionTask(this);
99
100         saver.setPref(PreferenceManager.getDefaultSharedPreferences(this));
101         LedgerTransaction tr = new LedgerTransaction(text_date.getText().toString(), text_descr.getText().toString());
102
103         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
104         for ( int i = 0; i < table.getChildCount(); i++ ) {
105             TableRow row = (TableRow) table.getChildAt(i);
106             String acc = ((TextView) row.getChildAt(0)).getText().toString();
107             String amt = ((TextView) row.getChildAt(1)).getText().toString();
108             LedgerTransactionItem item =
109                     amt.length() > 0
110                     ? new LedgerTransactionItem( acc, Float.parseFloat(amt))
111                     : new LedgerTransactionItem( acc );
112
113             tr.add_item(item);
114         }
115         saver.execute(tr);
116     }
117     private void hook_swipe_listener(final TableRow row) {
118         row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
119             public void onSwipeLeft() {
120 //                Log.d("swipe", "LEFT" + row.getId());
121                 if (table.getChildCount() > 2) {
122                     table.removeView(row);
123 //                    Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
124                 }
125                 else {
126                     Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required, Snackbar.LENGTH_LONG)
127                             .setAction("Action", null).show();
128                 }
129             }
130 //            @Override
131 //            public boolean performClick(View view, MotionEvent m) {
132 //                return true;
133 //            }
134             public boolean onTouch(View view, MotionEvent m) {
135                 return gestureDetector.onTouchEvent(m);
136             }
137         });
138     }
139
140     @TargetApi(Build.VERSION_CODES.N)
141     private void hook_autocompletion_adapter(final TableRow row) {
142         String[] from = {"name"};
143         int[] to = {android.R.id.text1};
144         SQLiteDatabase db = MobileLedgerDB.db;
145
146         AutoCompleteTextView acc = (AutoCompleteTextView) row.getChildAt(0);
147         SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null, from, to, 0);
148         adapter.setStringConversionColumn(1);
149
150         FilterQueryProvider provider = new FilterQueryProvider() {
151             @Override
152             public Cursor runQuery(CharSequence constraint) {
153                 if (constraint == null) return null;
154
155                 String str = constraint.toString().toUpperCase();
156                 Log.d("autocompletion", "Looking for "+str);
157                 String[] col_names = {FontsContract.Columns._ID, "name"};
158                 MatrixCursor c = new MatrixCursor(col_names);
159
160                 Cursor matches = db.rawQuery("SELECT name FROM accounts WHERE UPPER(name) LIKE '%'||?||'%' ORDER BY name;", new String[]{str});
161
162                 try {
163                     int i = 0;
164                     while (matches.moveToNext()) {
165                         String name = matches.getString(0);
166                         Log.d("autocompletion-match", name);
167                         c.newRow().add(i++).add(name);
168                     }
169                 }
170                 finally {
171                     matches.close();
172                 }
173
174                 return c;
175
176             }
177         };
178
179         adapter.setFilterQueryProvider(provider);
180
181         acc.setAdapter(adapter);
182     }
183
184     public boolean onCreateOptionsMenu(Menu menu) {
185         // Inflate the menu; this adds items to the action bar if it is present.
186         getMenuInflater().inflate(R.menu.new_transaction, menu);
187
188         return true;
189     }
190
191     public void pickTransactionDate(View view) {
192         DialogFragment picker = new DatePickerFragment();
193         picker.show(getSupportFragmentManager(), "datePicker");
194     }
195
196     public int dp2px(float dp) {
197         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
198     }
199
200     public void addTransactionAccountFromMenu(MenuItem item) {
201         final AutoCompleteTextView acc = new AutoCompleteTextView(this);
202         acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 9f));
203         acc.setHint(R.string.new_transaction_account_hint);
204         acc.setWidth(0);
205
206         final EditText amt = new EditText(this);
207         amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));
208         amt.setHint(R.string.new_transaction_amount_hint);
209         amt.setWidth(0);
210         amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL );
211         amt.setMinWidth(dp2px(40));
212         amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
213
214         final TableRow row = new TableRow(this);
215         row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
216         row.addView(acc);
217         row.addView(amt);
218         table.addView(row);
219
220         acc.requestFocus();
221
222         hook_swipe_listener(row);
223         hook_autocompletion_adapter(row);
224     }
225
226     @Override
227     public void done() {
228         fab.setImageResource(R.drawable.ic_check_white_24dp);
229         fab.setEnabled(true);
230
231         AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(this, R.animator.new_trans_animation);
232         set.setTarget(fab);
233         set.start();
234         final Handler at_fade_out = new Handler();
235         at_fade_out.postDelayed(new Runnable() {
236             @Override
237             public void run() {
238
239                 final Handler at_fade_in = new Handler();
240                 at_fade_in.postDelayed(new Runnable() {
241                     @Override
242                     public void run() {
243                         fab.setImageResource(R.drawable.ic_save_white_24dp);
244                     }
245                 }, 1000);
246             }
247         }, 500);
248         progress.setVisibility(View.INVISIBLE);
249         reset_form();
250     }
251
252     private void reset_form() {
253         text_date.setText("");
254         text_descr.setText("");
255         while(table.getChildCount() > 2) {
256             table.removeViewAt(2);
257         }
258         for( int i = 0; i < 2; i++ ) {
259             TableRow tr = (TableRow) table.getChildAt(i);
260             if ( tr == null) break;
261
262             ((TextView)tr.getChildAt(0)).setText("");
263             ((TextView)tr.getChildAt(1)).setText("");
264         }
265
266         text_descr.requestFocus();
267     }
268 }