]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/transaction_list/TransactionListAdapter.java
c61b9193d69e5071c781d43e122a4ab648524189
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / transaction_list / TransactionListAdapter.java
1 /*
2  * Copyright © 2020 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.app.Activity;
21 import android.content.Context;
22 import android.database.sqlite.SQLiteDatabase;
23 import android.graphics.Typeface;
24 import android.os.AsyncTask;
25 import android.text.Spannable;
26 import android.text.SpannableString;
27 import android.text.style.StyleSpan;
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 androidx.annotation.ColorInt;
35 import androidx.annotation.NonNull;
36 import androidx.recyclerview.widget.RecyclerView;
37
38 import net.ktnx.mobileledger.App;
39 import net.ktnx.mobileledger.R;
40 import net.ktnx.mobileledger.model.Data;
41 import net.ktnx.mobileledger.model.LedgerTransaction;
42 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
43 import net.ktnx.mobileledger.model.TransactionListItem;
44 import net.ktnx.mobileledger.utils.Colors;
45 import net.ktnx.mobileledger.utils.Globals;
46 import net.ktnx.mobileledger.utils.Misc;
47 import net.ktnx.mobileledger.utils.SimpleDate;
48
49 import java.text.DateFormat;
50 import java.util.GregorianCalendar;
51 import java.util.TimeZone;
52
53 public class TransactionListAdapter extends RecyclerView.Adapter<TransactionRowHolder> {
54     public void onBindViewHolder(@NonNull TransactionRowHolder holder, int position) {
55         TransactionListItem item = TransactionListViewModel.getTransactionListItem(position);
56
57         // in a race when transaction value is reduced, but the model hasn't been notified yet
58         // the view will disappear when the notifications reaches the model, so by simply omitting
59         // the out-of-range get() call nothing bad happens - just a to-be-deleted view remains
60         // a bit longer
61         if (item == null)
62             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
71                 //        accounts", position,
72                 //                tr.getAccounts().size()));
73
74                 TransactionLoader loader = new TransactionLoader();
75                 loader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
76                         new TransactionLoaderParams(tr, holder, position,
77                                 Data.accountFilter.getValue(), item.isOdd()));
78
79                 // WORKAROUND what seems to be a bug in CardHolder somewhere
80                 // when a view that was previously holding a delimiter is re-purposed
81                 // occasionally it stays too short (not high enough)
82                 holder.vTransaction.measure(
83                         View.MeasureSpec.makeMeasureSpec(holder.itemView.getWidth(),
84                                 View.MeasureSpec.EXACTLY),
85                         View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
86                 break;
87             case DELIMITER:
88                 SimpleDate date = item.getDate();
89                 holder.vTransaction.setVisibility(View.GONE);
90                 holder.vDelimiter.setVisibility(View.VISIBLE);
91                 holder.tvDelimiterDate.setText(DateFormat.getDateInstance()
92                                                          .format(date.toDate()));
93                 if (item.isMonthShown()) {
94                     GregorianCalendar cal = new GregorianCalendar(TimeZone.getDefault());
95                     cal.setTime(date.toDate());
96                     App.prepareMonthNames();
97                     holder.tvDelimiterMonth.setText(
98                             Globals.monthNames[cal.get(GregorianCalendar.MONTH)]);
99                     holder.tvDelimiterMonth.setVisibility(View.VISIBLE);
100                     //                holder.vDelimiterLine.setBackgroundResource(R.drawable
101                     //                .dashed_border_8dp);
102                     holder.vDelimiterThick.setVisibility(View.VISIBLE);
103                 }
104                 else {
105                     holder.tvDelimiterMonth.setVisibility(View.GONE);
106                     //                holder.vDelimiterLine.setBackgroundResource(R.drawable
107                     //                .dashed_border_1dp);
108                     holder.vDelimiterThick.setVisibility(View.GONE);
109                 }
110                 break;
111         }
112     }
113
114     @NonNull
115     @Override
116     public TransactionRowHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
117 //        debug("perf", "onCreateViewHolder called");
118         View row = LayoutInflater.from(parent.getContext())
119                                  .inflate(R.layout.transaction_list_row, parent, false);
120         return new TransactionRowHolder(row);
121     }
122
123     @Override
124     public int getItemCount() {
125         return Data.transactions.size();
126     }
127     enum LoaderStep {HEAD, ACCOUNTS, DONE}
128
129     private static class TransactionLoader
130             extends AsyncTask<TransactionLoaderParams, TransactionLoaderStep, Void> {
131         @Override
132         protected Void doInBackground(TransactionLoaderParams... p) {
133             LedgerTransaction tr = p[0].transaction;
134             boolean odd = p[0].odd;
135
136             SQLiteDatabase db = App.getDatabase();
137             tr.loadData(db);
138
139             publishProgress(new TransactionLoaderStep(p[0].holder, p[0].position, tr, odd));
140
141             int rowIndex = 0;
142             // FIXME ConcurrentModificationException in ArrayList$ltr.next (ArrayList.java:831)
143             for (LedgerTransactionAccount acc : tr.getAccounts()) {
144 //                debug(c.getAccountName(), acc.getAmount()));
145                 publishProgress(new TransactionLoaderStep(p[0].holder, acc, rowIndex++,
146                         p[0].boldAccountName));
147             }
148
149             publishProgress(new TransactionLoaderStep(p[0].holder, p[0].position, rowIndex));
150
151             return null;
152         }
153         @Override
154         protected void onProgressUpdate(TransactionLoaderStep... values) {
155             super.onProgressUpdate(values);
156             TransactionLoaderStep step = values[0];
157             TransactionRowHolder holder = step.getHolder();
158
159             switch (step.getStep()) {
160                 case HEAD:
161                     holder.tvDescription.setText(step.getTransaction()
162                                                      .getDescription());
163                     String trComment = Misc.emptyIsNull(step.getTransaction()
164                                                             .getComment());
165                     if (trComment == null)
166                         holder.tvComment.setVisibility(View.GONE);
167                     else {
168                         holder.tvComment.setText(trComment);
169                         holder.tvComment.setVisibility(View.VISIBLE);
170                     }
171
172 //                    if (step.isOdd())
173 //                        holder.row.setBackgroundColor(Colors.tableRowDarkBG);
174 //                    else
175 //                        holder.row.setBackgroundColor(Colors.tableRowLightBG);
176
177                     break;
178                 case ACCOUNTS:
179                     int rowIndex = step.getAccountPosition();
180                     Context ctx = holder.row.getContext();
181                     LinearLayout row = (LinearLayout) holder.tableAccounts.getChildAt(rowIndex);
182                     if (row == null) {
183                         LayoutInflater inflater = ((Activity) ctx).getLayoutInflater();
184                         row = (LinearLayout) inflater.inflate(
185                                 R.layout.transaction_list_row_accounts_table_row, null);
186                         // if the rootView above is given (and the line below is spared)
187                         // the accounts remain with their default text (set in the layout resource)
188                         holder.tableAccounts.addView(row);
189                     }
190                     TextView dummyText = row.findViewById(R.id.dummy_text);
191                     TextView accName = row.findViewById(R.id.transaction_list_acc_row_acc_name);
192                     TextView accComment =
193                             row.findViewById(R.id.transaction_list_acc_row_acc_comment);
194                     TextView accAmount = row.findViewById(R.id.transaction_list_acc_row_acc_amount);
195                     LedgerTransactionAccount acc = step.getAccount();
196
197
198 //                    debug("tmp", String.format("showing acc row %d: %s %1.2f", rowIndex,
199 //                            acc.getAccountName(), acc.getAmount()));
200
201                     String boldAccountName = step.getBoldAccountName();
202                     if ((boldAccountName != null) && acc.getAccountName()
203                                                         .startsWith(boldAccountName))
204                     {
205                         accName.setTextColor(Colors.secondary);
206                         accAmount.setTextColor(Colors.secondary);
207
208                         SpannableString ss = new SpannableString(acc.getAccountName());
209                         ss.setSpan(new StyleSpan(Typeface.BOLD), 0, boldAccountName.length(),
210                                 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
211                         accName.setText(ss);
212                     }
213                     else {
214                         @ColorInt int textColor = dummyText.getTextColors()
215                                                            .getDefaultColor();
216                         accName.setTextColor(textColor);
217                         accAmount.setTextColor(textColor);
218                         accName.setText(acc.getAccountName());
219                     }
220
221                     String comment = acc.getComment();
222                     if (comment != null && !comment.isEmpty()) {
223                         accComment.setText(comment);
224                         accComment.setVisibility(View.VISIBLE);
225                     }
226                     else {
227                         accComment.setVisibility(View.GONE);
228                     }
229                     accAmount.setText(acc.toString());
230
231                     break;
232                 case DONE:
233                     int accCount = step.getAccountCount();
234                     if (holder.tableAccounts.getChildCount() > accCount) {
235                         holder.tableAccounts.removeViews(accCount,
236                                 holder.tableAccounts.getChildCount() - accCount);
237                     }
238
239 //                    debug("transactions",
240 //                            String.format("Position %d fill done", step.getPosition()));
241             }
242         }
243     }
244
245     private class TransactionLoaderParams {
246         LedgerTransaction transaction;
247         TransactionRowHolder holder;
248         int position;
249         String boldAccountName;
250         boolean odd;
251         TransactionLoaderParams(LedgerTransaction transaction, TransactionRowHolder holder,
252                                 int position, String boldAccountName, boolean odd) {
253             this.transaction = transaction;
254             this.holder = holder;
255             this.position = position;
256             this.boldAccountName = boldAccountName;
257             this.odd = odd;
258         }
259     }
260 }