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