]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/transaction_list/TransactionListAdapter.java
move DB access routines to the application class
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / transaction_list / TransactionListAdapter.java
1 /*
2  * Copyright © 2019 Damyan Ivanov.
3  * This file is part of MoLe.
4  * MoLe is free software: you can distribute it and/or modify it
5  * under the term of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your opinion), any later version.
8  *
9  * MoLe is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License terms for details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.ui.transaction_list;
19
20 import android.content.Context;
21 import android.database.sqlite.SQLiteDatabase;
22 import android.graphics.Typeface;
23 import android.os.AsyncTask;
24 import android.text.Spannable;
25 import android.text.SpannableString;
26 import android.text.style.StyleSpan;
27 import android.view.Gravity;
28 import android.view.LayoutInflater;
29 import android.view.View;
30 import android.view.ViewGroup;
31 import android.widget.LinearLayout;
32 import android.widget.TextView;
33
34 import net.ktnx.mobileledger.App;
35 import net.ktnx.mobileledger.R;
36 import net.ktnx.mobileledger.model.Data;
37 import net.ktnx.mobileledger.model.LedgerTransaction;
38 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
39 import net.ktnx.mobileledger.model.TransactionListItem;
40 import net.ktnx.mobileledger.utils.Colors;
41 import net.ktnx.mobileledger.utils.Globals;
42
43 import java.text.DateFormat;
44 import java.util.Date;
45 import java.util.GregorianCalendar;
46 import java.util.TimeZone;
47
48 import androidx.annotation.NonNull;
49 import androidx.appcompat.widget.AppCompatTextView;
50 import androidx.recyclerview.widget.RecyclerView;
51
52 import static net.ktnx.mobileledger.utils.DimensionUtils.dp2px;
53
54 public class TransactionListAdapter extends RecyclerView.Adapter<TransactionRowHolder> {
55     public void onBindViewHolder(@NonNull TransactionRowHolder holder, int position) {
56         TransactionListItem item = TransactionListViewModel.getTransactionListItem(position);
57
58         // in a race when transaction value is reduced, but the model hasn't been notified yet
59         // the view will disappear when the notifications reaches the model, so by simply omitting
60         // the out-of-range get() call nothing bad happens - just a to-be-deleted view remains
61         // a bit longer
62         if (item == null) return;
63
64         switch (item.getType()) {
65             case TRANSACTION:
66                 holder.vTransaction.setVisibility(View.VISIBLE);
67                 holder.vDelimiter.setVisibility(View.GONE);
68                 LedgerTransaction tr = item.getTransaction();
69
70                 //        debug("transactions", String.format("Filling position %d with %d accounts", position,
71                 //                tr.getAccounts().size()));
72
73                 TransactionLoader loader = new TransactionLoader();
74                 loader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
75                         new TransactionLoaderParams(tr, holder, position, Data.accountFilter.getValue(),
76                                 item.isOdd()));
77
78                 // WORKAROUND what seems to be a bug in CardHolder somewhere
79                 // when a view that was previously holding a delimiter is re-purposed
80                 // occasionally it stays too short (not high enough)
81                 holder.vTransaction.measure(View.MeasureSpec
82                                 .makeMeasureSpec(holder.itemView.getWidth(), View.MeasureSpec.EXACTLY),
83                         View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
84                 break;
85             case DELIMITER:
86                 Date date = item.getDate();
87                 holder.vTransaction.setVisibility(View.GONE);
88                 holder.vDelimiter.setVisibility(View.VISIBLE);
89                 holder.tvDelimiterDate.setText(DateFormat.getDateInstance().format(date));
90                 if (item.isMonthShown()) {
91                     GregorianCalendar cal = new GregorianCalendar(TimeZone.getDefault());
92                     cal.setTime(date);
93                     holder.tvDelimiterMonth
94                             .setText(Globals.monthNames[cal.get(GregorianCalendar.MONTH)]);
95                     holder.tvDelimiterMonth.setVisibility(View.VISIBLE);
96                     //                holder.vDelimiterLine.setBackgroundResource(R.drawable.dashed_border_8dp);
97                     holder.vDelimiterLine.setVisibility(View.GONE);
98                     holder.vDelimiterThick.setVisibility(View.VISIBLE);
99                 }
100                 else {
101                     holder.tvDelimiterMonth.setVisibility(View.GONE);
102                     //                holder.vDelimiterLine.setBackgroundResource(R.drawable.dashed_border_1dp);
103                     holder.vDelimiterLine.setVisibility(View.VISIBLE);
104                     holder.vDelimiterThick.setVisibility(View.GONE);
105                 }
106                 break;
107         }
108     }
109
110     @NonNull
111     @Override
112     public TransactionRowHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
113 //        debug("perf", "onCreateViewHolder called");
114         View row = LayoutInflater.from(parent.getContext())
115                 .inflate(R.layout.transaction_list_row, parent, false);
116         return new TransactionRowHolder(row);
117     }
118
119     @Override
120     public int getItemCount() {
121         return Data.transactions.size();
122     }
123     enum LoaderStep {HEAD, ACCOUNTS, DONE}
124     private static class TransactionLoader
125             extends AsyncTask<TransactionLoaderParams, TransactionLoaderStep, Void> {
126         @Override
127         protected Void doInBackground(TransactionLoaderParams... p) {
128             LedgerTransaction tr = p[0].transaction;
129             boolean odd = p[0].odd;
130
131             SQLiteDatabase db = App.getDatabase();
132             tr.loadData(db);
133
134             publishProgress(new TransactionLoaderStep(p[0].holder, p[0].position, tr, odd));
135
136             int rowIndex = 0;
137             for (LedgerTransactionAccount acc : tr.getAccounts()) {
138 //                debug(c.getAccountName(), acc.getAmount()));
139                 publishProgress(new TransactionLoaderStep(p[0].holder, acc, rowIndex++,
140                         p[0].boldAccountName));
141             }
142
143             publishProgress(new TransactionLoaderStep(p[0].holder, p[0].position, rowIndex));
144
145             return null;
146         }
147         @Override
148         protected void onProgressUpdate(TransactionLoaderStep... values) {
149             super.onProgressUpdate(values);
150             TransactionLoaderStep step = values[0];
151             TransactionRowHolder holder = step.getHolder();
152
153             switch (step.getStep()) {
154                 case HEAD:
155                     holder.tvDescription.setText(step.getTransaction().getDescription());
156
157                     if (step.isOdd()) holder.row.setBackgroundColor(Colors.tableRowDarkBG);
158                     else holder.row.setBackgroundColor(Colors.tableRowLightBG);
159
160                     break;
161                 case ACCOUNTS:
162                     int rowIndex = step.getAccountPosition();
163                     Context ctx = holder.row.getContext();
164                     LinearLayout row = (LinearLayout) holder.tableAccounts.getChildAt(rowIndex);
165                     TextView accName, accAmount;
166                     if (row == null) {
167                         row = new LinearLayout(ctx);
168                         row.setLayoutParams(new LinearLayout.LayoutParams(
169                                 LinearLayout.LayoutParams.MATCH_PARENT,
170                                 LinearLayout.LayoutParams.WRAP_CONTENT));
171                         row.setGravity(Gravity.CENTER_VERTICAL);
172                         row.setOrientation(LinearLayout.HORIZONTAL);
173                         row.setPaddingRelative(dp2px(ctx, 8), 0, 0, 0);
174                         accName = new AppCompatTextView(ctx);
175                         accName.setLayoutParams(new LinearLayout.LayoutParams(0,
176                                 LinearLayout.LayoutParams.WRAP_CONTENT, 5f));
177                         accName.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_START);
178                         row.addView(accName);
179                         accAmount = new AppCompatTextView(ctx);
180                         LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(
181                                 LinearLayout.LayoutParams.WRAP_CONTENT,
182                                 LinearLayout.LayoutParams.WRAP_CONTENT);
183                         llp.setMarginEnd(0);
184                         accAmount.setLayoutParams(llp);
185                         accAmount.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_END);
186                         accAmount.setMinWidth(dp2px(ctx, 60));
187                         row.addView(accAmount);
188                         holder.tableAccounts.addView(row);
189                     }
190                     else {
191                         accName = (TextView) row.getChildAt(0);
192                         accAmount = (TextView) row.getChildAt(1);
193                     }
194                     LedgerTransactionAccount acc = step.getAccount();
195
196
197 //                    debug("tmp", String.format("showing acc row %d: %s %1.2f", rowIndex,
198 //                            acc.getAccountName(), acc.getAmount()));
199
200                     String boldAccountName = step.getBoldAccountName();
201                     if ((boldAccountName != null) &&
202                         acc.getAccountName().startsWith(boldAccountName))
203                     {
204                         accName.setTextColor(Colors.accent);
205                         accAmount.setTextColor(Colors.accent);
206
207                         SpannableString ss = new SpannableString(acc.getAccountName());
208                         ss.setSpan(new StyleSpan(Typeface.BOLD), 0, boldAccountName.length(),
209                                 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
210                         accName.setText(ss);
211                     }
212                     else {
213                         accName.setTextColor(Colors.defaultTextColor);
214                         accAmount.setTextColor(Colors.defaultTextColor);
215                         accName.setText(acc.getAccountName());
216                     }
217                     accAmount.setText(acc.toString());
218
219                     break;
220                 case DONE:
221                     int accCount = step.getAccountCount();
222                     if (holder.tableAccounts.getChildCount() > accCount) {
223                         holder.tableAccounts.removeViews(accCount,
224                                 holder.tableAccounts.getChildCount() - accCount);
225                     }
226
227 //                    debug("transactions",
228 //                            String.format("Position %d fill done", step.getPosition()));
229             }
230         }
231     }
232
233     private class TransactionLoaderParams {
234         LedgerTransaction transaction;
235         TransactionRowHolder holder;
236         int position;
237         String boldAccountName;
238         boolean odd;
239         TransactionLoaderParams(LedgerTransaction transaction, TransactionRowHolder holder,
240                                 int position, String boldAccountName, boolean odd) {
241             this.transaction = transaction;
242             this.holder = holder;
243             this.position = position;
244             this.boldAccountName = boldAccountName;
245             this.odd = odd;
246         }
247     }
248 }