1 package net.ktnx.mobileledger;
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.BaseTransientBottomBar;
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.Editable;
17 import android.text.InputType;
18 import android.text.TextWatcher;
19 import android.util.Log;
20 import android.util.TypedValue;
21 import android.view.Menu;
22 import android.view.MenuItem;
23 import android.view.MotionEvent;
24 import android.view.View;
25 import android.widget.AutoCompleteTextView;
26 import android.widget.EditText;
27 import android.widget.FilterQueryProvider;
28 import android.widget.ProgressBar;
29 import android.widget.SimpleCursorAdapter;
30 import android.widget.TableLayout;
31 import android.widget.TableRow;
32 import android.widget.TextView;
34 import java.util.Objects;
37 * TODO: auto-fill of transaction description
38 * if Android O's implementation won't work, add a custom one
39 * TODO: nicer progress while transaction is submitted
40 * TODO: latest transactions, maybe with browsing further in the past?
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)
45 * TODO: nicer swiping removal with visual feedback
47 * TODO: update accounts/check settings upon change of backend settings
50 public class NewTransactionActivity extends AppCompatActivity implements TaskCallback {
51 private TableLayout table;
52 private ProgressBar progress;
53 private TextView text_date;
54 private AutoCompleteTextView text_descr;
55 private static SaveTransactionTask saver;
56 private MenuItem mSave;
59 protected void onCreate(Bundle savedInstanceState) {
60 super.onCreate(savedInstanceState);
61 setContentView(R.layout.activity_new_transaction);
62 Toolbar toolbar = findViewById(R.id.toolbar);
63 setSupportActionBar(toolbar);
65 text_date = findViewById(R.id.new_transaction_date);
66 text_descr = findViewById(R.id.new_transaction_description);
67 hook_autocompletion_adapter(text_descr, MobileLedgerDB.DESCRIPTION_HISTORY_TABLE, "description");
69 progress = findViewById(R.id.save_transaction_progress);
71 Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
72 table = findViewById(R.id.new_transaction_accounts_table);
73 for (int i = 0; i < table.getChildCount(); i++) {
74 TableRow row = (TableRow) table.getChildAt(i);
75 AutoCompleteTextView acc_name_view = (AutoCompleteTextView) row.getChildAt(0);
76 TextView amount_view = (TextView) row.getChildAt(1);
77 hook_swipe_listener(row);
78 hook_autocompletion_adapter(acc_name_view, MobileLedgerDB.ACCOUNTS_TABLE, "name");
79 hook_text_change_listener(acc_name_view);
80 hook_text_change_listener(amount_view);
81 // Log.d("swipe", "hooked to row "+i);
86 public void finish() {
88 overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
92 public boolean onOptionsItemSelected(MenuItem item) {
93 switch (item.getItemId()) {
94 case android.R.id.home:
98 return super.onOptionsItemSelected(item);
101 public void save_transaction() {
102 if (mSave != null) mSave.setVisible(false);
103 toggle_all_editing(false);
104 progress.setVisibility(View.VISIBLE);
106 saver = new SaveTransactionTask(this);
108 saver.setPref(PreferenceManager.getDefaultSharedPreferences(this));
109 LedgerTransaction tr = new LedgerTransaction(text_date.getText().toString(), text_descr.getText().toString());
111 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
112 for ( int i = 0; i < table.getChildCount(); i++ ) {
113 TableRow row = (TableRow) table.getChildAt(i);
114 String acc = ((TextView) row.getChildAt(0)).getText().toString();
115 String amt = ((TextView) row.getChildAt(1)).getText().toString();
116 LedgerTransactionItem item =
118 ? new LedgerTransactionItem( acc, Float.parseFloat(amt))
119 : new LedgerTransactionItem( acc );
126 private void toggle_all_editing(boolean enabled) {
127 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
128 for (int i = 0; i < table.getChildCount(); i++) {
129 TableRow row = (TableRow) table.getChildAt(i);
130 for (int j = 0; j < row.getChildCount(); j++) {
131 row.getChildAt(j).setEnabled(enabled);
136 private void hook_swipe_listener(final TableRow row) {
137 row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
138 public void onSwipeLeft() {
139 // Log.d("swipe", "LEFT" + row.getId());
140 if (table.getChildCount() > 2) {
141 table.removeView(row);
142 // Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
145 Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required, Snackbar.LENGTH_LONG)
146 .setAction("Action", null).show();
150 // public boolean performClick(View view, MotionEvent m) {
153 public boolean onTouch(View view, MotionEvent m) {
154 return gestureDetector.onTouchEvent(m);
159 private void hook_text_change_listener(final TextView view) {
160 view.addTextChangedListener(new TextWatcher() {
162 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
167 public void onTextChanged(CharSequence s, int start, int before, int count) {
172 public void afterTextChanged(Editable s) {
173 // Log.d("input", "text changed");
174 check_transaction_submittable();
180 @TargetApi(Build.VERSION_CODES.N)
181 private void hook_autocompletion_adapter(final AutoCompleteTextView view, final String table, final String field) {
182 String[] from = {field};
183 int[] to = {android.R.id.text1};
184 SQLiteDatabase db = MobileLedgerDB.db;
186 SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null, from, to, 0);
187 adapter.setStringConversionColumn(1);
189 FilterQueryProvider provider = new FilterQueryProvider() {
191 public Cursor runQuery(CharSequence constraint) {
192 if (constraint == null) return null;
194 String str = constraint.toString().toUpperCase();
195 Log.d("autocompletion", "Looking for "+str);
196 String[] col_names = {FontsContract.Columns._ID, field};
197 MatrixCursor c = new MatrixCursor(col_names);
199 Cursor matches = db.rawQuery(String.format(
200 "SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
201 "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
202 "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end " +
203 "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' " +
204 "ORDER BY 2, 1;", field, field, field, field, table, field),
205 new String[]{str, str, str, str});
209 while (matches.moveToNext()) {
210 String match = matches.getString(0);
211 int order = matches.getInt(1);
212 Log.d("autocompletion", String.format("match: %s |%d", match, order));
213 c.newRow().add(i++).add(match);
225 adapter.setFilterQueryProvider(provider);
227 view.setAdapter(adapter);
230 public boolean onCreateOptionsMenu(Menu menu) {
231 // Inflate the menu; this adds items to the action bar if it is present.
232 getMenuInflater().inflate(R.menu.new_transaction, menu);
233 mSave = menu.findItem(R.id.action_submit_transaction);
234 if (mSave == null) throw new AssertionError();
239 public void pickTransactionDate(View view) {
240 DialogFragment picker = new DatePickerFragment();
241 picker.show(getSupportFragmentManager(), "datePicker");
244 public int dp2px(float dp) {
245 return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
248 private void do_add_account_row(boolean focus) {
249 final AutoCompleteTextView acc = new AutoCompleteTextView(this);
250 acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 9f));
251 acc.setHint(R.string.new_transaction_account_hint);
254 final EditText amt = new EditText(this);
255 amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));
256 amt.setHint(R.string.new_transaction_amount_hint);
258 amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL );
259 amt.setMinWidth(dp2px(40));
260 amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
262 final TableRow row = new TableRow(this);
263 row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
268 if (focus) acc.requestFocus();
270 hook_swipe_listener(row);
271 hook_autocompletion_adapter(acc, MobileLedgerDB.ACCOUNTS_TABLE, "name");
272 hook_text_change_listener(acc);
273 hook_text_change_listener(amt);
276 public void addTransactionAccountFromMenu(MenuItem item) {
277 do_add_account_row(true);
280 public void saveTransactionFromMenu(MenuItem item) {
284 private void check_transaction_submittable() {
285 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
287 int accounts_with_values = 0;
289 for(int i = 0; i < table.getChildCount(); i++ ) {
290 TableRow row = (TableRow) table.getChildAt(i);
292 TextView acc_name_v = (TextView) row.getChildAt(0);
294 String acc_name = String.valueOf(acc_name_v.getText());
295 acc_name = acc_name.trim();
296 if (!acc_name.isEmpty()) {
299 TextView amount_v = (TextView) row.getChildAt(1);
300 String amt = String.valueOf(amount_v.getText());
302 if (!amt.isEmpty()) accounts_with_values++;
306 if (accounts_with_values == accounts && empty_rows == 0) {
307 do_add_account_row(false);
310 if ((accounts >= 2) && (accounts_with_values >= (accounts - 1))) {
311 if (mSave != null) mSave.setVisible(true);
313 if (mSave != null) mSave.setVisible(false);
319 void done(String error) {
320 progress.setVisibility(View.INVISIBLE);
321 Log.d("visuals", "hiding progress");
323 if (error == null) reset_form();
324 else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
325 BaseTransientBottomBar.LENGTH_LONG).show();
327 toggle_all_editing(true);
328 check_transaction_submittable();
331 private void reset_form() {
332 text_date.setText("");
333 text_descr.setText("");
334 while(table.getChildCount() > 2) {
335 table.removeViewAt(2);
337 for( int i = 0; i < 2; i++ ) {
338 TableRow tr = (TableRow) table.getChildAt(i);
339 if ( tr == null) break;
341 ((TextView)tr.getChildAt(0)).setText("");
342 ((TextView)tr.getChildAt(1)).setText("");
345 text_descr.requestFocus();