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