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 table.removeAllViews();
82 do_add_account_row(false);
83 do_add_account_row(false);
87 public void finish() {
89 overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
93 public boolean onOptionsItemSelected(MenuItem item) {
94 switch (item.getItemId()) {
95 case android.R.id.home:
99 return super.onOptionsItemSelected(item);
102 public void save_transaction() {
103 if (mSave != null) mSave.setVisible(false);
104 toggle_all_editing(false);
105 progress.setVisibility(View.VISIBLE);
107 saver = new SaveTransactionTask(this);
109 saver.setPref(PreferenceManager.getDefaultSharedPreferences(this));
110 LedgerTransaction tr = new LedgerTransaction(text_date.getText().toString(), text_descr.getText().toString());
112 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
113 for ( int i = 0; i < table.getChildCount(); i++ ) {
114 TableRow row = (TableRow) table.getChildAt(i);
115 String acc = ((TextView) row.getChildAt(0)).getText().toString();
116 String amt = ((TextView) row.getChildAt(1)).getText().toString();
117 LedgerTransactionItem item =
119 ? new LedgerTransactionItem( acc, Float.parseFloat(amt))
120 : new LedgerTransactionItem( acc );
127 private void toggle_all_editing(boolean enabled) {
128 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
129 for (int i = 0; i < table.getChildCount(); i++) {
130 TableRow row = (TableRow) table.getChildAt(i);
131 for (int j = 0; j < row.getChildCount(); j++) {
132 row.getChildAt(j).setEnabled(enabled);
137 private void hook_swipe_listener(final TableRow row) {
138 row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
139 public void onSwipeLeft() {
140 // Log.d("swipe", "LEFT" + row.getId());
141 if (table.getChildCount() > 2) {
142 table.removeView(row);
143 // Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
146 Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required, Snackbar.LENGTH_LONG)
147 .setAction("Action", null).show();
151 // public boolean performClick(View view, MotionEvent m) {
154 public boolean onTouch(View view, MotionEvent m) {
155 return gestureDetector.onTouchEvent(m);
160 private void hook_text_change_listener(final TextView view) {
161 view.addTextChangedListener(new TextWatcher() {
163 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
168 public void onTextChanged(CharSequence s, int start, int before, int count) {
173 public void afterTextChanged(Editable s) {
174 // Log.d("input", "text changed");
175 check_transaction_submittable();
181 @TargetApi(Build.VERSION_CODES.N)
182 private void hook_autocompletion_adapter(final AutoCompleteTextView view, final String table, final String field) {
183 String[] from = {field};
184 int[] to = {android.R.id.text1};
185 SQLiteDatabase db = MobileLedgerDB.db;
187 SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null, from, to, 0);
188 adapter.setStringConversionColumn(1);
190 FilterQueryProvider provider = new FilterQueryProvider() {
192 public Cursor runQuery(CharSequence constraint) {
193 if (constraint == null) return null;
195 String str = constraint.toString().toUpperCase();
196 Log.d("autocompletion", "Looking for "+str);
197 String[] col_names = {FontsContract.Columns._ID, field};
198 MatrixCursor c = new MatrixCursor(col_names);
200 Cursor matches = db.rawQuery(String.format(
201 "SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
202 "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
203 "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end " +
204 "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' " +
205 "ORDER BY 2, 1;", field, field, field, field, table, field),
206 new String[]{str, str, str, str});
210 while (matches.moveToNext()) {
211 String match = matches.getString(0);
212 int order = matches.getInt(1);
213 Log.d("autocompletion", String.format("match: %s |%d", match, order));
214 c.newRow().add(i++).add(match);
226 adapter.setFilterQueryProvider(provider);
228 view.setAdapter(adapter);
231 public boolean onCreateOptionsMenu(Menu menu) {
232 // Inflate the menu; this adds items to the action bar if it is present.
233 getMenuInflater().inflate(R.menu.new_transaction, menu);
234 mSave = menu.findItem(R.id.action_submit_transaction);
235 if (mSave == null) throw new AssertionError();
237 check_transaction_submittable();
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,
259 TableRow.LayoutParams.MATCH_PARENT, 1f));
260 amt.setHint(R.string.new_transaction_amount_hint);
262 amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL );
263 amt.setMinWidth(dp2px(40));
264 amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
266 final TableRow row = new TableRow(this);
267 row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
268 row.setGravity(Gravity.BOTTOM);
273 if (focus) acc.requestFocus();
275 hook_swipe_listener(row);
276 hook_autocompletion_adapter(acc, MobileLedgerDB.ACCOUNTS_TABLE, "name");
277 hook_text_change_listener(acc);
278 hook_text_change_listener(amt);
281 public void addTransactionAccountFromMenu(MenuItem item) {
282 do_add_account_row(true);
285 public void saveTransactionFromMenu(MenuItem item) {
289 private void check_transaction_submittable() {
290 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
292 int accounts_with_values = 0;
294 for(int i = 0; i < table.getChildCount(); i++ ) {
295 TableRow row = (TableRow) table.getChildAt(i);
297 TextView acc_name_v = (TextView) row.getChildAt(0);
299 String acc_name = String.valueOf(acc_name_v.getText());
300 acc_name = acc_name.trim();
301 if (!acc_name.isEmpty()) {
304 TextView amount_v = (TextView) row.getChildAt(1);
305 String amt = String.valueOf(amount_v.getText());
307 if (!amt.isEmpty()) accounts_with_values++;
311 if (accounts_with_values == accounts && empty_rows == 0) {
312 do_add_account_row(false);
315 if ((accounts >= 2) && (accounts_with_values >= (accounts - 1))) {
316 if (mSave != null) mSave.setVisible(true);
318 if (mSave != null) mSave.setVisible(false);
324 void done(String error) {
325 progress.setVisibility(View.INVISIBLE);
326 Log.d("visuals", "hiding progress");
328 if (error == null) reset_form();
329 else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
330 BaseTransientBottomBar.LENGTH_LONG).show();
332 toggle_all_editing(true);
333 check_transaction_submittable();
336 private void reset_form() {
337 text_date.setText("");
338 text_descr.setText("");
339 while(table.getChildCount() > 2) {
340 table.removeViewAt(2);
342 for( int i = 0; i < 2; i++ ) {
343 TableRow tr = (TableRow) table.getChildAt(i);
344 if ( tr == null) break;
346 ((TextView)tr.getChildAt(0)).setText("");
347 ((TextView)tr.getChildAt(1)).setText("");
350 text_descr.requestFocus();