]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/transaction_list/TransactionListAdapter.java
3946474f35bd245a3079d5e704b713a45a895073
[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.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
47 import java.text.DateFormat;
48 import java.util.Date;
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                 Date date = item.getDate();
88                 holder.vTransaction.setVisibility(View.GONE);
89                 holder.vDelimiter.setVisibility(View.VISIBLE);
90                 holder.tvDelimiterDate.setText(DateFormat.getDateInstance()
91                                                          .format(date));
92                 if (item.isMonthShown()) {
93                     GregorianCalendar cal = new GregorianCalendar(TimeZone.getDefault());
94                     cal.setTime(date);
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.vDelimiterLine.setVisibility(View.GONE);
101                     holder.vDelimiterThick.setVisibility(View.VISIBLE);
102                 }
103                 else {
104                     holder.tvDelimiterMonth.setVisibility(View.GONE);
105                     //                holder.vDelimiterLine.setBackgroundResource(R.drawable
106                     //                .dashed_border_1dp);
107                     holder.vDelimiterLine.setVisibility(View.VISIBLE);
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 accName = row.findViewById(R.id.transaction_list_acc_row_acc_name);
191                     TextView accComment =
192                             row.findViewById(R.id.transaction_list_acc_row_acc_comment);
193                     TextView accAmount = row.findViewById(R.id.transaction_list_acc_row_acc_amount);
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) && acc.getAccountName()
202                                                         .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
218                     String comment = acc.getComment();
219                     if (comment != null && !comment.isEmpty()) {
220                         accComment.setText(comment);
221                         accComment.setVisibility(View.VISIBLE);
222                     }
223                     else {
224                         accComment.setVisibility(View.GONE);
225                     }
226                     accAmount.setText(acc.toString());
227
228                     break;
229                 case DONE:
230                     int accCount = step.getAccountCount();
231                     if (holder.tableAccounts.getChildCount() > accCount) {
232                         holder.tableAccounts.removeViews(accCount,
233                                 holder.tableAccounts.getChildCount() - accCount);
234                     }
235
236 //                    debug("transactions",
237 //                            String.format("Position %d fill done", step.getPosition()));
238             }
239         }
240     }
241
242     private class TransactionLoaderParams {
243         LedgerTransaction transaction;
244         TransactionRowHolder holder;
245         int position;
246         String boldAccountName;
247         boolean odd;
248         TransactionLoaderParams(LedgerTransaction transaction, TransactionRowHolder holder,
249                                 int position, String boldAccountName, boolean odd) {
250             this.transaction = transaction;
251             this.holder = holder;
252             this.position = position;
253             this.boldAccountName = boldAccountName;
254             this.odd = odd;
255         }
256     }
257 }