Reputation: 133
I have a list of transaction history from an API, which I display in a RecyclerView. But I want to loop through all the date and group items with the same date together and display only one of the dates on in the recyclerview.
JSON Response
{
"_id": "5ebxxxxx8af9xxxxxxxxxxcf9",
"user": "5ebxxxxx8af9xxxxxxxxxxcf9",
"transactionType": "earn",
"transactionAmount": 100,
"refId": "cvry65nyj7u7a",
"createdAt": "2020-05-19T08:34:42.528Z",
"updatedAt": "2020-05-19T08:34:42.528Z",
"__v": 0
},
{
"_id": "5ebxxxxx8af9xxxxxxxxxxcf9",
"user": "5ebxxxxx8af9xxxxxxxxxxcf9",
"transactionType": "earn",
"transactionAmount": 100,
"refId": "bghyj5t4efm7",
"createdAt": "2020-05-19T08:34:42.528Z",
"updatedAt": "2020-05-19T08:34:42.528Z",
"__v": 0
},
{
"_id": "5ebxxxxx8af9xxxxxxxxxxcf9",
"user": "5ebxxxxx8af9xxxxxxxxxxcf9",
"transactionType": "earn",
"transactionAmount": 100,
"refId": "3kin7cHdcdvbfxhcxr3dM",
"createdAt": "2020-05-17T08:34:42.528Z",
"updatedAt": "2020-05-17T08:34:42.528Z",
"__v": 0
},
{
"_id": "5ebxxxxx8af9xxxxxxxxxxcf9",
"user": "5ebxxxxx8af9xxxxxxxxxxcf9",
"transactionType": "earn",
"transactionAmount": 100,
"refId": "3kin7cHxjbdfuhcxr3dM",
"createdAt": "2020-05-17T08:34:42.528Z",
"updatedAt": "2020-05-17T08:34:42.528Z",
"__v": 0
},
Here is the loop I tried using but it doesn't work
for (int i = 0; i <= txnList.size(); i++) {
String dateCart = txnList.get(i).getCreatedAt();
holder.txnDate.setVisibility(View.VISIBLE);
for (int j = 0; j <= i ; j++) {
if (dateCart.equalsIgnoreCase(txnList.get(j).getCreatedAt())) {
holder.txnDate.setVisibility(View.GONE);
}
}
}
I want the UI to be display like below
Same date| txn type
txn amount
| txn type
txn amount
| txn type
txn amount
Same data | txn type
txn amount
| txn type
txn amount
How do I go about this?
Upvotes: 0
Views: 1043
Reputation: 9225
First sort your list, Add Sorting list code in your activity or fragment class
Collections.sort(txnList, new Comparator<TxnBeen>() {
public int compare(TxnBeen o1, TxnBeen o2) {
if (o1.getCreatedAt() == null || o2.getCreatedAt() == null)
return 0;
return o1.getCreatedAt().compareTo(o2.getCreatedAt());
}
});
then set this sorted list to your adapter.
In Adapter class under onBindViewHolder
function check same created at date:
if (position == 0) {
String ts1 = txnList.get(position).getCreatedAt();
String ts2 = "";
boolean sameDate = ts1.equalsIgnoreCase(ts2);
if(sameDate){
holder.txnDate.setVisibility(View.GONE);
}else {
holder.txnDate.setVisibility(View.VISIBLE);
holder.txnDate.setText(ts1);
}
}else{
String ts1 = txnList.get(position).getCreatedAt();
String ts2 = txnList.get(position-1).getCreatedAt();;
boolean sameDate = ts1.equalsIgnoreCase(ts2);
if(sameDate){
holder.txnDate.setVisibility(View.GONE);
}else {
holder.txnDate.setVisibility(View.VISIBLE);
holder.txnDate.setText(ts1);
}
}
Upvotes: 1