Reputation: 2069
I'm getting the list of user ids from database. And its getting the values correctly. I'm using FirebaseRecyclerAdapter
and when I iterate that list in onBindViewHolder
the loops runs as the size of list. For example over here :
adapter = new FirebaseRecyclerAdapter<Profiles, DonarViewHolder>(model) {
@Override
protected void onBindViewHolder(@NonNull DonarViewHolder holder, int position, @NonNull Profiles profiles) {
for (int i = 0 ; i<list.size() ; i++){
Toast.makeText(List.this,"List :" +list.get(i), Toast.LENGTH_SHORT).show();
}
}
}
Over here I have 5 item in list and while iterating I'm toasting each item . So in here the loop run for 25 time, its shows each item 5 time in sequence. First it shows 5 items orderly after showing last item it start toasting from first one again and continues till 5 time as the size of list. So how do I cater this and make it only iterate the whole items for once only?
Upvotes: 0
Views: 348
Reputation: 2877
onBindViewHolder
is called by RecyvlerView
to display the data at the specified position. Since you have all the data in a List
, their corresponding index will be the same as the position of the itemView
.
In your function, you are iterating over all the items in the list
for each itemView
which the ViewHolder
is generating.
You have to remove the for
loop from your code and simply use the position
as the index
to retrieve data from your list
, whose index
is same as position
.
Try this code:
adapter = new FirebaseRecyclerAdapter<Profiles, DonarViewHolder>(model) {
@Override
protected void onBindViewHolder(@NonNull DonarViewHolder holder, int position, @NonNull Profiles profiles) {
Toast.makeText(List.this,"List :" +list.get(position), Toast.LENGTH_SHORT).show();
}
}
For this method, every time an itemView
is generated, it will be at a position
and with this as an index, you can easily get the data from the list
.
For your scenario, since you are already inside each itemView
being generated inside the onBindViewHolder
, and then you are iterating for each element in your list
, hence every item is being displayed exactly the same number of times, as the size of the list
.
Upvotes: 2
Reputation: 25
I think you are missing a method that you can use to call each item individually. create a setter and getter for your item. In your loop you can then call it list.get(position).getItem .
Upvotes: 1