I'm having a RecyclerView, inside its layout there's a view "tvDateGrouped", I want it to be displayed only when the current position date and previous position date are not same. Below is the code I tried, but it isn't working
This Code is inside the adapter class, inside the onBind() method
if (position != 0 && transactions[position].date ==
transactions[holder.adapterPosition.minus(1)].date) {
holder.view.tvDateGrouped.visibility = View.GONE
} else {
holder.view.tvDateGrouped.text = formattedDateString
}
and if I change position != 1 , the app crashes
below is the code when app crashes
if (position != 1 && transactions[position].date ==
transactions[holder.adapterPosition.minus(1)].date) {
holder.view.tvDateGrouped.visibility = View.GONE
} else {
holder.view.tvDateGrouped.text = formattedDateString
}
Edit: I've changed the code as the below, but the app is crashing now-
if ((transactions[position].date == transactions[position - 1].date) &&
(position > 0)) {
holder.view.tvDateGrouped.visibility = View.GONE
} else {
holder.view.tvDateGrouped.visibility = View.VISIBLE
holder.view.tvDateGrouped.text = formattedDateString
}
Please Help me resolve this issue
Your crash is simply happening when position
is 0
then position - 1
will be -1
which is an invalid index and you will get a runtime exception.
But why the first solution isn't working? One clear reason is because you've forgotten to make the text visible again. So change it to:
if (position > 0 && transactions[position].date == transactions[position - 1].date) {
holder.view.tvDateGrouped.visibility = View.GONE
} else {
holder.view.tvDateGrouped.visibility = View.VISIBLE
holder.view.tvDateGrouped.text = formattedDateString
}