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.Gravity;
22 import android.view.Menu;
23 import android.view.MenuItem;
24 import android.view.MotionEvent;
25 import android.view.View;
26 import android.widget.AutoCompleteTextView;
27 import android.widget.EditText;
28 import android.widget.FilterQueryProvider;
29 import android.widget.ProgressBar;
30 import android.widget.SimpleCursorAdapter;
31 import android.widget.TableLayout;
32 import android.widget.TableRow;
33 import android.widget.TextView;
35 import java.util.Objects;
38 * TODO: auto-fill of transaction description
39 * if Android O's implementation won't work, add a custom one
40 * TODO: nicer progress while transaction is submitted
41 * TODO: latest transactions, maybe with browsing further in the past?
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)
46 * TODO: nicer swiping removal with visual feedback
48 * TODO: update accounts/check settings upon change of backend settings
51 public class NewTransactionActivity extends AppCompatActivity implements TaskCallback {
52 private TableLayout table;
53 private ProgressBar progress;
54 private TextView text_date;
55 private AutoCompleteTextView text_descr;
56 private static SaveTransactionTask saver;
57 private MenuItem mSave;
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);
66 text_date = findViewById(R.id.new_transaction_date);
67 text_date.setOnFocusChangeListener(new View.OnFocusChangeListener() {
70 void onFocusChange(View v, boolean hasFocus) {
71 if (hasFocus) pickTransactionDate(v);
74 text_descr = findViewById(R.id.new_transaction_description);
75 hook_autocompletion_adapter(text_descr, MobileLedgerDB.DESCRIPTION_HISTORY_TABLE, "description");
77 progress = findViewById(R.id.save_transaction_progress);
79 Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
80 table = findViewById(R.id.new_transaction_accounts_table);
81 for (int i = 0; i < table.getChildCount(); i++) {
82 TableRow row = (TableRow) table.getChildAt(i);
83 AutoCompleteTextView acc_name_view = (AutoCompleteTextView) row.getChildAt(0);
84 TextView amount_view = (TextView) row.getChildAt(1);
85 hook_swipe_listener(row);
86 hook_autocompletion_adapter(acc_name_view, MobileLedgerDB.ACCOUNTS_TABLE, "name");
87 hook_text_change_listener(acc_name_view);
88 hook_text_change_listener(amount_view);
89 // Log.d("swipe", "hooked to row "+i);
94 public void finish() {
96 overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
100 public boolean onOptionsItemSelected(MenuItem item) {
101 switch (item.getItemId()) {
102 case android.R.id.home:
106 return super.onOptionsItemSelected(item);
109 public void save_transaction() {
110 if (mSave != null) mSave.setVisible(false);
111 toggle_all_editing(false);
112 progress.setVisibility(View.VISIBLE);
114 saver = new SaveTransactionTask(this);
116 saver.setPref(PreferenceManager.getDefaultSharedPreferences(this));
117 LedgerTransaction tr = new LedgerTransaction(text_date.getText().toString(), text_descr.getText().toString());
119 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
120 for ( int i = 0; i < table.getChildCount(); i++ ) {
121 TableRow row = (TableRow) table.getChildAt(i);
122 String acc = ((TextView) row.getChildAt(0)).getText().toString();
123 String amt = ((TextView) row.getChildAt(1)).getText().toString();
124 LedgerTransactionItem item =
126 ? new LedgerTransactionItem( acc, Float.parseFloat(amt))
127 : new LedgerTransactionItem( acc );
134 private void toggle_all_editing(boolean enabled) {
135 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
136 for (int i = 0; i < table.getChildCount(); i++) {
137 TableRow row = (TableRow) table.getChildAt(i);
138 for (int j = 0; j < row.getChildCount(); j++) {
139 row.getChildAt(j).setEnabled(enabled);
144 private void hook_swipe_listener(final TableRow row) {
145 row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
146 public void onSwipeLeft() {
147 // Log.d("swipe", "LEFT" + row.getId());
148 if (table.getChildCount() > 2) {
149 table.removeView(row);
150 // Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
153 Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required, Snackbar.LENGTH_LONG)
154 .setAction("Action", null).show();
158 // public boolean performClick(View view, MotionEvent m) {
161 public boolean onTouch(View view, MotionEvent m) {
162 return gestureDetector.onTouchEvent(m);
167 private void hook_text_change_listener(final TextView view) {
168 view.addTextChangedListener(new TextWatcher() {
170 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
175 public void onTextChanged(CharSequence s, int start, int before, int count) {
180 public void afterTextChanged(Editable s) {
181 // Log.d("input", "text changed");
182 check_transaction_submittable();
188 @TargetApi(Build.VERSION_CODES.N)
189 private void hook_autocompletion_adapter(final AutoCompleteTextView view, final String table, final String field) {
190 String[] from = {field};
191 int[] to = {android.R.id.text1};
192 SQLiteDatabase db = MobileLedgerDB.db;
194 SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null, from, to, 0);
195 adapter.setStringConversionColumn(1);
197 FilterQueryProvider provider = new FilterQueryProvider() {
199 public Cursor runQuery(CharSequence constraint) {
200 if (constraint == null) return null;
202 String str = constraint.toString().toUpperCase();
203 Log.d("autocompletion", "Looking for "+str);
204 String[] col_names = {FontsContract.Columns._ID, field};
205 MatrixCursor c = new MatrixCursor(col_names);
207 Cursor matches = db.rawQuery(String.format(
208 "SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
209 "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
210 "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end " +
211 "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' " +
212 "ORDER BY 2, 1;", field, field, field, field, table, field),
213 new String[]{str, str, str, str});
217 while (matches.moveToNext()) {
218 String match = matches.getString(0);
219 int order = matches.getInt(1);
220 Log.d("autocompletion", String.format("match: %s |%d", match, order));
221 c.newRow().add(i++).add(match);
233 adapter.setFilterQueryProvider(provider);
235 view.setAdapter(adapter);
238 public boolean onCreateOptionsMenu(Menu menu) {
239 // Inflate the menu; this adds items to the action bar if it is present.
240 getMenuInflater().inflate(R.menu.new_transaction, menu);
241 mSave = menu.findItem(R.id.action_submit_transaction);
242 if (mSave == null) throw new AssertionError();
244 check_transaction_submittable();
249 public void pickTransactionDate(View view) {
250 DialogFragment picker = new DatePickerFragment();
251 picker.show(getSupportFragmentManager(), "datePicker");
254 public int dp2px(float dp) {
255 return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
258 private void do_add_account_row(boolean focus) {
259 final AutoCompleteTextView acc = new AutoCompleteTextView(this);
260 acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 9f));
261 acc.setHint(R.string.new_transaction_account_hint);
264 final EditText amt = new EditText(this);
265 amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
266 TableRow.LayoutParams.MATCH_PARENT, 1f));
267 amt.setHint(R.string.new_transaction_amount_hint);
269 amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL );
270 amt.setMinWidth(dp2px(40));
271 amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
273 final TableRow row = new TableRow(this);
274 row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
275 row.setGravity(Gravity.BOTTOM);
280 if (focus) acc.requestFocus();
282 hook_swipe_listener(row);
283 hook_autocompletion_adapter(acc, MobileLedgerDB.ACCOUNTS_TABLE, "name");
284 hook_text_change_listener(acc);
285 hook_text_change_listener(amt);
288 public void addTransactionAccountFromMenu(MenuItem item) {
289 do_add_account_row(true);
292 public void saveTransactionFromMenu(MenuItem item) {
296 private void check_transaction_submittable() {
297 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
299 int accounts_with_values = 0;
301 for(int i = 0; i < table.getChildCount(); i++ ) {
302 TableRow row = (TableRow) table.getChildAt(i);
304 TextView acc_name_v = (TextView) row.getChildAt(0);
306 String acc_name = String.valueOf(acc_name_v.getText());
307 acc_name = acc_name.trim();
308 if (!acc_name.isEmpty()) {
311 TextView amount_v = (TextView) row.getChildAt(1);
312 String amt = String.valueOf(amount_v.getText());
314 if (!amt.isEmpty()) accounts_with_values++;
318 if (accounts_with_values == accounts && empty_rows == 0) {
319 do_add_account_row(false);
322 if ((accounts >= 2) && (accounts_with_values >= (accounts - 1))) {
323 if (mSave != null) mSave.setVisible(true);
325 if (mSave != null) mSave.setVisible(false);
331 void done(String error) {
332 progress.setVisibility(View.INVISIBLE);
333 Log.d("visuals", "hiding progress");
335 if (error == null) reset_form();
336 else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
337 BaseTransientBottomBar.LENGTH_LONG).show();
339 toggle_all_editing(true);
340 check_transaction_submittable();
343 private void reset_form() {
344 text_date.setText("");
345 text_descr.setText("");
346 while(table.getChildCount() > 2) {
347 table.removeViewAt(2);
349 for( int i = 0; i < 2; i++ ) {
350 TableRow tr = (TableRow) table.getChildAt(i);
351 if ( tr == null) break;
353 ((TextView)tr.getChildAt(0)).setText("");
354 ((TextView)tr.getChildAt(1)).setText("");
357 text_descr.requestFocus();