]> git.ktnx.net Git - mobile-ledger-staging.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/transaction_list/TransactionListAdapter.java
fix many lint errors/warnings
[mobile-ledger-staging.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.AsyncListDiffer;
37 import androidx.recyclerview.widget.DiffUtil;
38 import androidx.recyclerview.widget.RecyclerView;
39
40 import net.ktnx.mobileledger.App;
41 import net.ktnx.mobileledger.R;
42 import net.ktnx.mobileledger.model.LedgerTransaction;
43 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
44 import net.ktnx.mobileledger.model.TransactionListItem;
45 import net.ktnx.mobileledger.ui.MainModel;
46 import net.ktnx.mobileledger.utils.Colors;
47 import net.ktnx.mobileledger.utils.Globals;
48 import net.ktnx.mobileledger.utils.Logger;
49 import net.ktnx.mobileledger.utils.Misc;
50 import net.ktnx.mobileledger.utils.SimpleDate;
51
52 import java.text.DateFormat;
53 import java.util.GregorianCalendar;
54 import java.util.List;
55 import java.util.Locale;
56 import java.util.TimeZone;
57
58 public class TransactionListAdapter extends RecyclerView.Adapter<TransactionRowHolder> {
59     private final MainModel model;
60     private final AsyncListDiffer<TransactionListItem> listDiffer;
61     public TransactionListAdapter(MainModel model) {
62         super();
63         this.model = model;
64
65         listDiffer = new AsyncListDiffer<>(this, new DiffUtil.ItemCallback<TransactionListItem>() {
66             @Override
67             public boolean areItemsTheSame(@NonNull TransactionListItem oldItem,
68                                            @NonNull TransactionListItem newItem) {
69                 if (oldItem.getType() != newItem.getType())
70                     return false;
71                 switch (oldItem.getType()) {
72                     case DELIMITER:
73                         return (oldItem.getDate()
74                                        .equals(newItem.getDate()));
75                     case TRANSACTION:
76                         return oldItem.getTransaction()
77                                       .getId() == newItem.getTransaction()
78                                                          .getId();
79                     default:
80                         throw new IllegalStateException(
81                                 String.format(Locale.US, "Unexpected transaction item type %s",
82                                         oldItem.getType()));
83                 }
84             }
85             @Override
86             public boolean areContentsTheSame(@NonNull TransactionListItem oldItem,
87                                               @NonNull TransactionListItem newItem) {
88                 switch (oldItem.getType()) {
89                     case DELIMITER:
90                         // Delimiters items are "same" for same dates and the contents are the date
91                         return true;
92                     case TRANSACTION:
93                         return oldItem.getTransaction()
94                                       .equals(newItem.getTransaction());
95                     default:
96                         throw new IllegalStateException(
97                                 String.format(Locale.US, "Unexpected transaction item type %s",
98                                         oldItem.getType()));
99
100                 }
101             }
102         });
103     }
104     public void onBindViewHolder(@NonNull TransactionRowHolder holder, int position) {
105         TransactionListItem item = listDiffer.getCurrentList()
106                                              .get(position);
107
108         // in a race when transaction value is reduced, but the model hasn't been notified yet
109         // the view will disappear when the notifications reaches the model, so by simply omitting
110         // the out-of-range get() call nothing bad happens - just a to-be-deleted view remains
111         // a bit longer
112         if (item == null)
113             return;
114
115         switch (item.getType()) {
116             case TRANSACTION:
117                 holder.vTransaction.setVisibility(View.VISIBLE);
118                 holder.vDelimiter.setVisibility(View.GONE);
119                 LedgerTransaction tr = item.getTransaction();
120
121                 //        debug("transactions", String.format("Filling position %d with %d
122                 //        accounts", position,
123                 //                tr.getAccounts().size()));
124
125                 TransactionLoader loader = new TransactionLoader();
126                 loader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
127                         new TransactionLoaderParams(tr, holder, position, model.getAccountFilter()
128                                                                                .getValue()));
129
130                 // WORKAROUND what seems to be a bug in CardHolder somewhere
131                 // when a view that was previously holding a delimiter is re-purposed
132                 // occasionally it stays too short (not high enough)
133                 holder.vTransaction.measure(
134                         View.MeasureSpec.makeMeasureSpec(holder.itemView.getWidth(),
135                                 View.MeasureSpec.EXACTLY),
136                         View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
137                 break;
138             case DELIMITER:
139                 SimpleDate date = item.getDate();
140                 holder.vTransaction.setVisibility(View.GONE);
141                 holder.vDelimiter.setVisibility(View.VISIBLE);
142                 holder.tvDelimiterDate.setText(DateFormat.getDateInstance()
143                                                          .format(date.toDate()));
144                 if (item.isMonthShown()) {
145                     GregorianCalendar cal = new GregorianCalendar(TimeZone.getDefault());
146                     cal.setTime(date.toDate());
147                     App.prepareMonthNames();
148                     holder.tvDelimiterMonth.setText(
149                             Globals.monthNames[cal.get(GregorianCalendar.MONTH)]);
150                     holder.tvDelimiterMonth.setVisibility(View.VISIBLE);
151                     //                holder.vDelimiterLine.setBackgroundResource(R.drawable
152                     //                .dashed_border_8dp);
153                     holder.vDelimiterThick.setVisibility(View.VISIBLE);
154                 }
155                 else {
156                     holder.tvDelimiterMonth.setVisibility(View.GONE);
157                     //                holder.vDelimiterLine.setBackgroundResource(R.drawable
158                     //                .dashed_border_1dp);
159                     holder.vDelimiterThick.setVisibility(View.GONE);
160                 }
161                 break;
162         }
163     }
164
165     @NonNull
166     @Override
167     public TransactionRowHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
168 //        debug("perf", "onCreateViewHolder called");
169         View row = LayoutInflater.from(parent.getContext())
170                                  .inflate(R.layout.transaction_list_row, parent, false);
171         return new TransactionRowHolder(row);
172     }
173
174     @Override
175     public int getItemCount() {
176         return listDiffer.getCurrentList()
177                          .size();
178     }
179     public void setTransactions(List<TransactionListItem> newList) {
180         Logger.debug("transactions",
181                 String.format(Locale.US, "Got new transaction list (%d items)", newList.size()));
182         listDiffer.submitList(newList);
183     }
184     enum LoaderStep {HEAD, ACCOUNTS, DONE}
185
186     private static class TransactionLoader
187             extends AsyncTask<TransactionLoaderParams, TransactionLoaderStep, Void> {
188         @Override
189         protected Void doInBackground(TransactionLoaderParams... p) {
190             LedgerTransaction tr = p[0].transaction;
191
192             SQLiteDatabase db = App.getDatabase();
193             tr.loadData(db);
194
195             publishProgress(new TransactionLoaderStep(p[0].holder, p[0].position, tr));
196
197             int rowIndex = 0;
198             // FIXME ConcurrentModificationException in ArrayList$ltr.next (ArrayList.java:831)
199             for (LedgerTransactionAccount acc : tr.getAccounts()) {
200 //                debug(c.getAccountName(), acc.getAmount()));
201                 publishProgress(new TransactionLoaderStep(p[0].holder, acc, rowIndex++,
202                         p[0].boldAccountName));
203             }
204
205             publishProgress(new TransactionLoaderStep(p[0].holder, p[0].position, rowIndex));
206
207             return null;
208         }
209         @Override
210         protected void onProgressUpdate(TransactionLoaderStep... values) {
211             super.onProgressUpdate(values);
212             TransactionLoaderStep step = values[0];
213             TransactionRowHolder holder = step.getHolder();
214
215             switch (step.getStep()) {
216                 case HEAD:
217                     holder.tvDescription.setText(step.getTransaction()
218                                                      .getDescription());
219                     String trComment = Misc.emptyIsNull(step.getTransaction()
220                                                             .getComment());
221                     if (trComment == null)
222                         holder.tvComment.setVisibility(View.GONE);
223                     else {
224                         holder.tvComment.setText(trComment);
225                         holder.tvComment.setVisibility(View.VISIBLE);
226                     }
227
228 //                    if (step.isOdd())
229 //                        holder.row.setBackgroundColor(Colors.tableRowDarkBG);
230 //                    else
231 //                        holder.row.setBackgroundColor(Colors.tableRowLightBG);
232
233                     break;
234                 case ACCOUNTS:
235                     int rowIndex = step.getAccountPosition();
236                     Context ctx = holder.row.getContext();
237                     LinearLayout row = (LinearLayout) holder.tableAccounts.getChildAt(rowIndex);
238                     if (row == null) {
239                         row = new LinearLayout(ctx);
240                         LayoutInflater inflater = ((Activity) ctx).getLayoutInflater();
241                         inflater.inflate(R.layout.transaction_list_row_accounts_table_row, row);
242                         holder.tableAccounts.addView(row);
243                     }
244                     TextView dummyText = row.findViewById(R.id.dummy_text);
245                     TextView accName = row.findViewById(R.id.transaction_list_acc_row_acc_name);
246                     TextView accComment =
247                             row.findViewById(R.id.transaction_list_acc_row_acc_comment);
248                     TextView accAmount = row.findViewById(R.id.transaction_list_acc_row_acc_amount);
249                     LedgerTransactionAccount acc = step.getAccount();
250
251
252 //                    debug("tmp", String.format("showing acc row %d: %s %1.2f", rowIndex,
253 //                            acc.getAccountName(), acc.getAmount()));
254
255                     String boldAccountName = step.getBoldAccountName();
256                     if ((boldAccountName != null) && acc.getAccountName()
257                                                         .startsWith(boldAccountName))
258                     {
259                         accName.setTextColor(Colors.secondary);
260                         accAmount.setTextColor(Colors.secondary);
261
262                         SpannableString ss = new SpannableString(acc.getAccountName());
263                         ss.setSpan(new StyleSpan(Typeface.BOLD), 0, boldAccountName.length(),
264                                 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
265                         accName.setText(ss);
266                     }
267                     else {
268                         @ColorInt int textColor = dummyText.getTextColors()
269                                                            .getDefaultColor();
270                         accName.setTextColor(textColor);
271                         accAmount.setTextColor(textColor);
272                         accName.setText(acc.getAccountName());
273                     }
274
275                     String comment = acc.getComment();
276                     if (comment != null && !comment.isEmpty()) {
277                         accComment.setText(comment);
278                         accComment.setVisibility(View.VISIBLE);
279                     }
280                     else {
281                         accComment.setVisibility(View.GONE);
282                     }
283                     accAmount.setText(acc.toString());
284
285                     break;
286                 case DONE:
287                     int accCount = step.getAccountCount();
288                     if (holder.tableAccounts.getChildCount() > accCount) {
289                         holder.tableAccounts.removeViews(accCount,
290                                 holder.tableAccounts.getChildCount() - accCount);
291                     }
292
293 //                    debug("transactions",
294 //                            String.format("Position %d fill done", step.getPosition()));
295             }
296         }
297     }
298
299     private static class TransactionLoaderParams {
300         final LedgerTransaction transaction;
301         final TransactionRowHolder holder;
302         final int position;
303         final String boldAccountName;
304         TransactionLoaderParams(LedgerTransaction transaction, TransactionRowHolder holder,
305                                 int position, String boldAccountName) {
306             this.transaction = transaction;
307             this.holder = holder;
308             this.position = position;
309             this.boldAccountName = boldAccountName;
310         }
311     }
312 }