1 package net.ktnx.mobileledger;
3 import android.annotation.SuppressLint;
4 import android.annotation.TargetApi;
5 import android.database.Cursor;
6 import android.database.MatrixCursor;
7 import android.database.sqlite.SQLiteDatabase;
8 import android.os.Build;
9 import android.os.Bundle;
10 import android.preference.PreferenceManager;
11 import android.provider.FontsContract;
12 import android.support.design.widget.BaseTransientBottomBar;
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.Gravity;
23 import android.view.Menu;
24 import android.view.MenuItem;
25 import android.view.MotionEvent;
26 import android.view.View;
27 import android.widget.AutoCompleteTextView;
28 import android.widget.EditText;
29 import android.widget.FilterQueryProvider;
30 import android.widget.ProgressBar;
31 import android.widget.SimpleCursorAdapter;
32 import android.widget.TableLayout;
33 import android.widget.TableRow;
34 import android.widget.TextView;
36 import java.util.Date;
37 import java.util.Objects;
40 * TODO: auto-fill of transaction description
41 * if Android O's implementation won't work, add a custom one
42 * TODO: nicer progress while transaction is submitted
43 * TODO: latest transactions, maybe with browsing further in the past?
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)
48 * TODO: nicer swiping removal with visual feedback
50 * TODO: update accounts/check settings upon change of backend settings
53 public class NewTransactionActivity extends AppCompatActivity implements TaskCallback {
54 private TableLayout table;
55 private ProgressBar progress;
56 private TextView text_date;
57 private AutoCompleteTextView text_descr;
58 private static SaveTransactionTask saver;
59 private MenuItem mSave;
62 protected void onCreate(Bundle savedInstanceState) {
63 super.onCreate(savedInstanceState);
64 setContentView(R.layout.activity_new_transaction);
65 Toolbar toolbar = findViewById(R.id.toolbar);
66 setSupportActionBar(toolbar);
68 text_date = findViewById(R.id.new_transaction_date);
69 text_date.setOnFocusChangeListener(new View.OnFocusChangeListener() {
72 void onFocusChange(View v, boolean hasFocus) {
73 if (hasFocus) pickTransactionDate(v);
76 text_descr = findViewById(R.id.new_transaction_description);
77 hook_autocompletion_adapter(text_descr, MobileLedgerDB.DESCRIPTION_HISTORY_TABLE, "description");
78 hook_text_change_listener(text_descr);
80 progress = findViewById(R.id.save_transaction_progress);
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 TableRow row = (TableRow) table.getChildAt(i);
86 AutoCompleteTextView acc_name_view = (AutoCompleteTextView) row.getChildAt(0);
87 TextView amount_view = (TextView) row.getChildAt(1);
88 hook_swipe_listener(row);
89 hook_autocompletion_adapter(acc_name_view, MobileLedgerDB.ACCOUNTS_TABLE, "name");
90 hook_text_change_listener(acc_name_view);
91 hook_text_change_listener(amount_view);
92 // Log.d("swipe", "hooked to row "+i);
97 public void finish() {
99 overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
103 public boolean onOptionsItemSelected(MenuItem item) {
104 switch (item.getItemId()) {
105 case android.R.id.home:
109 return super.onOptionsItemSelected(item);
112 public void save_transaction() {
113 if (mSave != null) mSave.setVisible(false);
114 toggle_all_editing(false);
115 progress.setVisibility(View.VISIBLE);
117 saver = new SaveTransactionTask(this);
119 saver.setPref(PreferenceManager.getDefaultSharedPreferences(this));
120 String date = text_date.getText().toString();
121 if (date.isEmpty()) date = String.valueOf(new Date().getDate());
122 LedgerTransaction tr = new LedgerTransaction(date, text_descr.getText().toString());
124 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
125 for ( int i = 0; i < table.getChildCount(); i++ ) {
126 TableRow row = (TableRow) table.getChildAt(i);
127 String acc = ((TextView) row.getChildAt(0)).getText().toString();
128 String amt = ((TextView) row.getChildAt(1)).getText().toString();
129 LedgerTransactionItem item =
131 ? new LedgerTransactionItem( acc, Float.parseFloat(amt))
132 : new LedgerTransactionItem( acc );
139 private void toggle_all_editing(boolean enabled) {
140 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
141 for (int i = 0; i < table.getChildCount(); i++) {
142 TableRow row = (TableRow) table.getChildAt(i);
143 for (int j = 0; j < row.getChildCount(); j++) {
144 row.getChildAt(j).setEnabled(enabled);
149 private void hook_swipe_listener(final TableRow row) {
150 row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
151 public void onSwipeLeft() {
152 // Log.d("swipe", "LEFT" + row.getId());
153 if (table.getChildCount() > 2) {
154 table.removeView(row);
155 // Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
158 Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required, Snackbar.LENGTH_LONG)
159 .setAction("Action", null).show();
163 // public boolean performClick(View view, MotionEvent m) {
166 public boolean onTouch(View view, MotionEvent m) {
167 return gestureDetector.onTouchEvent(m);
172 private void hook_text_change_listener(final TextView view) {
173 view.addTextChangedListener(new TextWatcher() {
175 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
180 public void onTextChanged(CharSequence s, int start, int before, int count) {
185 public void afterTextChanged(Editable s) {
186 // Log.d("input", "text changed");
187 check_transaction_submittable();
193 @TargetApi(Build.VERSION_CODES.N)
194 private void hook_autocompletion_adapter(final AutoCompleteTextView view, final String table, final String field) {
195 String[] from = {field};
196 int[] to = {android.R.id.text1};
197 SQLiteDatabase db = MobileLedgerDB.db;
199 SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null, from, to, 0);
200 adapter.setStringConversionColumn(1);
202 FilterQueryProvider provider = new FilterQueryProvider() {
204 public Cursor runQuery(CharSequence constraint) {
205 if (constraint == null) return null;
207 String str = constraint.toString().toUpperCase();
208 Log.d("autocompletion", "Looking for "+str);
209 String[] col_names = {FontsContract.Columns._ID, field};
210 MatrixCursor c = new MatrixCursor(col_names);
212 Cursor matches = db.rawQuery(String.format(
213 "SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
214 "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
215 "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end " +
216 "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' " +
217 "ORDER BY 2, 1;", field, field, field, field, table, field),
218 new String[]{str, str, str, str});
222 while (matches.moveToNext()) {
223 String match = matches.getString(0);
224 int order = matches.getInt(1);
225 Log.d("autocompletion", String.format("match: %s |%d", match, order));
226 c.newRow().add(i++).add(match);
238 adapter.setFilterQueryProvider(provider);
240 view.setAdapter(adapter);
243 public boolean onCreateOptionsMenu(Menu menu) {
244 // Inflate the menu; this adds items to the action bar if it is present.
245 getMenuInflater().inflate(R.menu.new_transaction, menu);
246 mSave = menu.findItem(R.id.action_submit_transaction);
247 if (mSave == null) throw new AssertionError();
249 check_transaction_submittable();
254 public void pickTransactionDate(View view) {
255 DialogFragment picker = new DatePickerFragment();
256 picker.show(getSupportFragmentManager(), "datePicker");
259 public int dp2px(float dp) {
260 return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
263 private void do_add_account_row(boolean focus) {
264 final AutoCompleteTextView acc = new AutoCompleteTextView(this);
265 acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 9f));
266 acc.setHint(R.string.new_transaction_account_hint);
269 final EditText amt = new EditText(this);
270 amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
271 TableRow.LayoutParams.MATCH_PARENT, 1f));
272 amt.setHint(R.string.new_transaction_amount_hint);
274 amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL );
275 amt.setMinWidth(dp2px(40));
276 amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
278 final TableRow row = new TableRow(this);
279 row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
280 row.setGravity(Gravity.BOTTOM);
285 if (focus) acc.requestFocus();
287 hook_swipe_listener(row);
288 hook_autocompletion_adapter(acc, MobileLedgerDB.ACCOUNTS_TABLE, "name");
289 hook_text_change_listener(acc);
290 hook_text_change_listener(amt);
293 public void addTransactionAccountFromMenu(MenuItem item) {
294 do_add_account_row(true);
298 void resetTransactionFromMenu(MenuItem item) {
302 public void saveTransactionFromMenu(MenuItem item) {
307 // 1) at least two account names
308 // 2) each amount must have account name
309 // 3) amounts must balance to 0, or
310 // 3a) there must be exactly one empty amount
311 // 4) empty accounts with empty amounts are ignored
312 // 5) a row with an empty account name or empty amount is guaranteed to exist
313 @SuppressLint("DefaultLocale")
314 private void check_transaction_submittable() {
315 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
317 int accounts_with_values = 0;
319 int amounts_with_accounts = 0;
321 TextView empty_amount = null;
322 boolean single_empty_amount = false;
323 float running_total = 0f;
324 boolean have_description =
325 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
329 for (int i = 0; i < table.getChildCount(); i++) {
330 TableRow row = (TableRow) table.getChildAt(i);
332 TextView acc_name_v = (TextView) row.getChildAt(0);
333 TextView amount_v = (TextView) row.getChildAt(1);
334 String amt = String.valueOf(amount_v.getText());
335 String acc_name = String.valueOf(acc_name_v.getText());
336 acc_name = acc_name.trim();
338 if (!acc_name.isEmpty()) {
341 if (!amt.isEmpty()) {
342 accounts_with_values++;
348 amount_v.setHint(String.format("%1.2f", 0f));
349 if (empty_amount == null) {
350 empty_amount = amount_v;
351 single_empty_amount = true;
353 else if (!acc_name.isEmpty()) single_empty_amount = false;
357 if (!acc_name.isEmpty()) amounts_with_accounts++;
358 running_total += Float.valueOf(amt);
362 if ((empty_rows == 0) && ((table.getChildCount() == accounts) || (table.getChildCount()
365 do_add_account_row(false);
368 if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) && (
369 amounts_with_accounts == amounts))
371 if (mSave != null) mSave.setVisible(true);
373 else if (mSave != null) mSave.setVisible(false);
375 if (single_empty_amount) {
377 .setHint(String.format("%1.2f", (running_total > 0) ? -running_total : 0f));
380 catch (NumberFormatException e) {
381 if (mSave != null) mSave.setVisible(false);
383 catch (Exception e) {
385 if (mSave != null) mSave.setVisible(false);
391 void done(String error) {
392 progress.setVisibility(View.INVISIBLE);
393 Log.d("visuals", "hiding progress");
395 if (error == null) reset_form();
396 else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
397 BaseTransientBottomBar.LENGTH_LONG).show();
399 toggle_all_editing(true);
400 check_transaction_submittable();
403 private void reset_form() {
404 text_date.setText("");
405 text_descr.setText("");
407 text_descr.requestFocus();
409 while(table.getChildCount() > 2) {
410 table.removeViewAt(2);
412 for( int i = 0; i < 2; i++ ) {
413 TableRow tr = (TableRow) table.getChildAt(i);
414 if ( tr == null) break;
416 ((TextView)tr.getChildAt(0)).setText("");
417 ((TextView)tr.getChildAt(1)).setText("");