]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/NewTransactionActivity.java
progress bar around the save transaction floating action button
[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.preference.PreferenceManager;
10 import android.provider.FontsContract;
11 import android.support.design.widget.FloatingActionButton;
12 import android.support.design.widget.Snackbar;
13 import android.support.v4.app.DialogFragment;
14 import android.support.v7.app.AppCompatActivity;
15 import android.support.v7.widget.Toolbar;
16 import android.text.InputType;
17 import android.util.Log;
18 import android.util.TypedValue;
19 import android.view.Menu;
20 import android.view.MenuItem;
21 import android.view.MotionEvent;
22 import android.view.View;
23 import android.widget.AutoCompleteTextView;
24 import android.widget.EditText;
25 import android.widget.FilterQueryProvider;
26 import android.widget.ProgressBar;
27 import android.widget.SimpleCursorAdapter;
28 import android.widget.TableLayout;
29 import android.widget.TableRow;
30 import android.widget.TextView;
31
32 import java.util.Objects;
33
34 /*
35  * TODO: auto-fill of transaction description
36  *       if Android O's implementation won't work, add a custom one
37  * TODO: nicer progress while transaction is submitted
38  * TODO: periodic and manual refresh of available accounts
39  *         (now done forcibly each time the main activity is started)
40  * TODO: latest transactions, maybe with browsing further in the past?
41  * TODO: reports
42  * TODO: get rid of the custom session/cookie and auth code?
43  *         (the last problem with the POST was the missing content-length header)
44  * TODO: app icon
45  * TODO: nicer swiping removal with visual feedback
46  * TODO: activity with current balance
47  * TODO: setup wizard
48  * TODO: update accounts/check settings upon change of backend settings
49  *  */
50
51 public class NewTransactionActivity extends AppCompatActivity implements TaskCallback {
52     private TableLayout table;
53     private FloatingActionButton fab;
54     private ProgressBar progress;
55     private TextView text_date;
56     private TextView text_descr;
57     private static SaveTransactionTask saver;
58
59     @Override
60     protected void onCreate(Bundle savedInstanceState) {
61         super.onCreate(savedInstanceState);
62         setContentView(R.layout.activity_new_transaction);
63         Toolbar toolbar = findViewById(R.id.toolbar);
64         setSupportActionBar(toolbar);
65
66         text_date = findViewById(R.id.new_transaction_date);
67         text_descr = findViewById(R.id.new_transaction_description);
68
69         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
70             text_descr.setAutofillHints("");
71         }
72
73         fab = findViewById(R.id.fab);
74         fab.setOnClickListener(new View.OnClickListener() {
75             @Override
76             public void onClick(View view) {
77                 new_transaction_save_clicked(view);
78             }
79         });
80         progress = findViewById(R.id.save_transaction_progress);
81
82         Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
83         table = findViewById(R.id.new_transaction_accounts_table);
84         for (int i = 0; i < table.getChildCount(); i++) {
85             hook_swipe_listener((TableRow)table.getChildAt(i));
86             hook_autocompletion_adapter((TableRow)table.getChildAt(i));
87 //            Log.d("swipe", "hooked to row "+i);
88         }
89     }
90
91     public void new_transaction_save_clicked(View view) {
92         fab.setEnabled(false);
93         progress.setVisibility(View.VISIBLE);
94
95         saver = new SaveTransactionTask(this);
96
97         saver.setPref(PreferenceManager.getDefaultSharedPreferences(this));
98         LedgerTransaction tr = new LedgerTransaction(text_date.getText().toString(), text_descr.getText().toString());
99
100         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
101         for ( int i = 0; i < table.getChildCount(); i++ ) {
102             TableRow row = (TableRow) table.getChildAt(i);
103             String acc = ((TextView) row.getChildAt(0)).getText().toString();
104             String amt = ((TextView) row.getChildAt(1)).getText().toString();
105             LedgerTransactionItem item =
106                     amt.length() > 0
107                     ? new LedgerTransactionItem( acc, Float.parseFloat(amt))
108                     : new LedgerTransactionItem( acc );
109
110             tr.add_item(item);
111         }
112         saver.execute(tr);
113     }
114     private void hook_swipe_listener(final TableRow row) {
115         row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
116             public void onSwipeLeft() {
117 //                Log.d("swipe", "LEFT" + row.getId());
118                 if (table.getChildCount() > 2) {
119                     table.removeView(row);
120 //                    Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
121                 }
122                 else {
123                     Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required, Snackbar.LENGTH_LONG)
124                             .setAction("Action", null).show();
125                 }
126             }
127 //            @Override
128 //            public boolean performClick(View view, MotionEvent m) {
129 //                return true;
130 //            }
131             public boolean onTouch(View view, MotionEvent m) {
132                 return gestureDetector.onTouchEvent(m);
133             }
134         });
135     }
136
137     @TargetApi(Build.VERSION_CODES.N)
138     private void hook_autocompletion_adapter(final TableRow row) {
139         String[] from = {"name"};
140         int[] to = {android.R.id.text1};
141         SQLiteDatabase db = MobileLedgerDB.db;
142
143         AutoCompleteTextView acc = (AutoCompleteTextView) row.getChildAt(0);
144         SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null, from, to, 0);
145         adapter.setStringConversionColumn(1);
146
147         FilterQueryProvider provider = new FilterQueryProvider() {
148             @Override
149             public Cursor runQuery(CharSequence constraint) {
150                 if (constraint == null) return null;
151
152                 String str = constraint.toString().toUpperCase();
153                 Log.d("autocompletion", "Looking for "+str);
154                 String[] col_names = {FontsContract.Columns._ID, "name"};
155                 MatrixCursor c = new MatrixCursor(col_names);
156
157                 Cursor matches = db.rawQuery("SELECT name FROM accounts WHERE UPPER(name) LIKE '%'||?||'%' ORDER BY name;", new String[]{str});
158
159                 try {
160                     int i = 0;
161                     while (matches.moveToNext()) {
162                         String name = matches.getString(0);
163                         Log.d("autocompletion-match", name);
164                         c.newRow().add(i++).add(name);
165                     }
166                 }
167                 finally {
168                     matches.close();
169                 }
170
171                 return c;
172
173             }
174         };
175
176         adapter.setFilterQueryProvider(provider);
177
178         acc.setAdapter(adapter);
179     }
180
181     public boolean onCreateOptionsMenu(Menu menu) {
182         // Inflate the menu; this adds items to the action bar if it is present.
183         getMenuInflater().inflate(R.menu.new_transaction, menu);
184
185         return true;
186     }
187
188     public void pickTransactionDate(View view) {
189         DialogFragment picker = new DatePickerFragment();
190         picker.show(getSupportFragmentManager(), "datePicker");
191     }
192
193     public int dp2px(float dp) {
194         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
195     }
196
197     public void addTransactionAccountFromMenu(MenuItem item) {
198         final AutoCompleteTextView acc = new AutoCompleteTextView(this);
199         acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 9f));
200         acc.setHint(R.string.new_transaction_account_hint);
201         acc.setWidth(0);
202
203         final EditText amt = new EditText(this);
204         amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));
205         amt.setHint(R.string.new_transaction_amount_hint);
206         amt.setWidth(0);
207         amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL );
208         amt.setMinWidth(dp2px(40));
209         amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
210
211         final TableRow row = new TableRow(this);
212         row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
213         row.addView(acc);
214         row.addView(amt);
215         table.addView(row);
216
217         acc.requestFocus();
218
219         hook_swipe_listener(row);
220         hook_autocompletion_adapter(row);
221     }
222
223     @Override
224     public void done() {
225         fab.setEnabled(true);
226         progress.setVisibility(View.INVISIBLE);
227         reset_form();
228     }
229
230     private void reset_form() {
231         text_date.setText("");
232         text_descr.setText("");
233         while(table.getChildCount() > 2) {
234             table.removeViewAt(2);
235         }
236         for( int i = 0; i < 2; i++ ) {
237             TableRow tr = (TableRow) table.getChildAt(i);
238             if ( tr == null) break;
239
240             ((TextView)tr.getChildAt(0)).setText("");
241             ((TextView)tr.getChildAt(1)).setText("");
242         }
243
244         text_descr.requestFocus();
245     }
246 }