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: periodic and manual refresh of available accounts
41 * (now done forcibly each time the main activity is started)
42 * TODO: latest transactions, maybe with browsing further in the past?
44 * TODO: get rid of the custom session/cookie and auth code?
45 * (the last problem with the POST was the missing content-length header)
47 * TODO: nicer swiping removal with visual feedback
48 * TODO: activity with current balance
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_descr = findViewById(R.id.new_transaction_description);
70 hook_autocompletion_adapter(text_descr, MobileLedgerDB.DESCRIPTION_HISTORY_TABLE, "description");
72 progress = findViewById(R.id.save_transaction_progress);
74 Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
75 table = findViewById(R.id.new_transaction_accounts_table);
76 for (int i = 0; i < table.getChildCount(); i++) {
77 TableRow row = (TableRow) table.getChildAt(i);
78 AutoCompleteTextView acc_name_view = (AutoCompleteTextView) row.getChildAt(0);
79 TextView amount_view = (TextView) row.getChildAt(1);
80 hook_swipe_listener(row);
81 hook_autocompletion_adapter(acc_name_view, MobileLedgerDB.ACCOUNTS_TABLE, "name");
82 hook_text_change_listener(acc_name_view);
83 hook_text_change_listener(amount_view);
84 // Log.d("swipe", "hooked to row "+i);
89 public void finish() {
91 overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
95 public boolean onOptionsItemSelected(MenuItem item) {
96 switch (item.getItemId()) {
97 case android.R.id.home:
101 return super.onOptionsItemSelected(item);
104 public void save_transaction() {
105 if (mSave != null) mSave.setVisible(false);
106 toggle_all_editing(false);
107 progress.setVisibility(View.VISIBLE);
109 saver = new SaveTransactionTask(this);
111 saver.setPref(PreferenceManager.getDefaultSharedPreferences(this));
112 LedgerTransaction tr = new LedgerTransaction(text_date.getText().toString(), text_descr.getText().toString());
114 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
115 for ( int i = 0; i < table.getChildCount(); i++ ) {
116 TableRow row = (TableRow) table.getChildAt(i);
117 String acc = ((TextView) row.getChildAt(0)).getText().toString();
118 String amt = ((TextView) row.getChildAt(1)).getText().toString();
119 LedgerTransactionItem item =
121 ? new LedgerTransactionItem( acc, Float.parseFloat(amt))
122 : new LedgerTransactionItem( acc );
129 private void toggle_all_editing(boolean enabled) {
130 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
131 for (int i = 0; i < table.getChildCount(); i++) {
132 TableRow row = (TableRow) table.getChildAt(i);
133 for (int j = 0; j < row.getChildCount(); j++) {
134 row.getChildAt(j).setEnabled(enabled);
139 private void hook_swipe_listener(final TableRow row) {
140 row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
141 public void onSwipeLeft() {
142 // Log.d("swipe", "LEFT" + row.getId());
143 if (table.getChildCount() > 2) {
144 table.removeView(row);
145 // Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
148 Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required, Snackbar.LENGTH_LONG)
149 .setAction("Action", null).show();
153 // public boolean performClick(View view, MotionEvent m) {
156 public boolean onTouch(View view, MotionEvent m) {
157 return gestureDetector.onTouchEvent(m);
162 private void hook_text_change_listener(final TextView view) {
163 view.addTextChangedListener(new TextWatcher() {
165 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
170 public void onTextChanged(CharSequence s, int start, int before, int count) {
175 public void afterTextChanged(Editable s) {
176 // Log.d("input", "text changed");
177 check_transaction_submittable();
183 @TargetApi(Build.VERSION_CODES.N)
184 private void hook_autocompletion_adapter(final AutoCompleteTextView view, final String table, final String field) {
185 String[] from = {field};
186 int[] to = {android.R.id.text1};
187 SQLiteDatabase db = MobileLedgerDB.db;
189 SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null, from, to, 0);
190 adapter.setStringConversionColumn(1);
192 FilterQueryProvider provider = new FilterQueryProvider() {
194 public Cursor runQuery(CharSequence constraint) {
195 if (constraint == null) return null;
197 String str = constraint.toString().toUpperCase();
198 Log.d("autocompletion", "Looking for "+str);
199 String[] col_names = {FontsContract.Columns._ID, field};
200 MatrixCursor c = new MatrixCursor(col_names);
202 Cursor matches = db.rawQuery(String.format(
203 "SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
204 "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
205 "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end " +
206 "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' " +
207 "ORDER BY 2, 1;", field, field, field, field, table, field),
208 new String[]{str, str, str, str});
212 while (matches.moveToNext()) {
213 String match = matches.getString(0);
214 int order = matches.getInt(1);
215 Log.d("autocompletion", String.format("match: %s |%d", match, order));
216 c.newRow().add(i++).add(match);
228 adapter.setFilterQueryProvider(provider);
230 view.setAdapter(adapter);
233 public boolean onCreateOptionsMenu(Menu menu) {
234 // Inflate the menu; this adds items to the action bar if it is present.
235 getMenuInflater().inflate(R.menu.new_transaction, menu);
236 mSave = menu.findItem(R.id.action_submit_transaction);
237 if (mSave == null) throw new AssertionError();
242 public void pickTransactionDate(View view) {
243 DialogFragment picker = new DatePickerFragment();
244 picker.show(getSupportFragmentManager(), "datePicker");
247 public int dp2px(float dp) {
248 return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
251 private void do_add_account_row(boolean focus) {
252 final AutoCompleteTextView acc = new AutoCompleteTextView(this);
253 acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 9f));
254 acc.setHint(R.string.new_transaction_account_hint);
257 final EditText amt = new EditText(this);
258 amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));
259 amt.setHint(R.string.new_transaction_amount_hint);
261 amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL );
262 amt.setMinWidth(dp2px(40));
263 amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
265 final TableRow row = new TableRow(this);
266 row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
271 if (focus) acc.requestFocus();
273 hook_swipe_listener(row);
274 hook_autocompletion_adapter(acc, MobileLedgerDB.ACCOUNTS_TABLE, "name");
275 hook_text_change_listener(acc);
276 hook_text_change_listener(amt);
279 public void addTransactionAccountFromMenu(MenuItem item) {
280 do_add_account_row(true);
283 public void saveTransactionFromMenu(MenuItem item) {
287 private void check_transaction_submittable() {
288 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
290 int accounts_with_values = 0;
292 for(int i = 0; i < table.getChildCount(); i++ ) {
293 TableRow row = (TableRow) table.getChildAt(i);
295 TextView acc_name_v = (TextView) row.getChildAt(0);
297 String acc_name = String.valueOf(acc_name_v.getText());
298 acc_name = acc_name.trim();
299 if (!acc_name.isEmpty()) {
302 TextView amount_v = (TextView) row.getChildAt(1);
303 String amt = String.valueOf(amount_v.getText());
305 if (!amt.isEmpty()) accounts_with_values++;
309 if (accounts_with_values == accounts && empty_rows == 0) {
310 do_add_account_row(false);
313 if ((accounts >= 2) && (accounts_with_values >= (accounts - 1))) {
314 if (mSave != null) mSave.setVisible(true);
316 if (mSave != null) mSave.setVisible(false);
322 void done(String error) {
323 progress.setVisibility(View.INVISIBLE);
324 Log.d("visuals", "hiding progress");
326 if (error == null) reset_form();
327 else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
328 BaseTransientBottomBar.LENGTH_LONG).show();
330 toggle_all_editing(true);
331 check_transaction_submittable();
334 private void reset_form() {
335 text_date.setText("");
336 text_descr.setText("");
337 while(table.getChildCount() > 2) {
338 table.removeViewAt(2);
340 for( int i = 0; i < 2; i++ ) {
341 TableRow tr = (TableRow) table.getChildAt(i);
342 if ( tr == null) break;
344 ((TextView)tr.getChildAt(0)).setText("");
345 ((TextView)tr.getChildAt(1)).setText("");
348 text_descr.requestFocus();