I have a problem regarding RecyclerView duplicating its items on scroll to top.
My RecyclerView
populates its View
by taking values from an online database on scroll down to a certain threshold. I am well aware of RecyclerView
's behavior on reusing the Views
, but I don't want that to happen as it'll get confusing due to having Views
with different items inside.
I've searched around SO for the solution. Some said that I have to override getItemId
like :
@Override
public long getItemId(int id) {
return id;
}
But they don't elaborate more on that.
Tried using setHasStableIds(true);
but it's not working. When I scroll down to populate the RecyclerView
, then scroll quickly back up, the first item still shows the last item I scrolled to, or any other random item.
I have this in onBindViewHolder
:
if(loading)
{
// Do nothing
}
else {
((ObjectViewHolder) holder).progressBar.setVisibility(View.GONE);
((ObjectViewHolder) holder).postListWrapper.setVisibility(View.VISIBLE);
Uri userImageUri = Uri.parse(mDataset.get(position).author_avatar);
...
// The rest of the code
}
Does it have to do with the error I'm getting? The loading is changed to false when the Fragment
containing RecyclerView
finished getting value from the database.
Here's the RecyclerView
onScrollListener
:
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int firstVisibleItem = manager.findFirstCompletelyVisibleItemPosition();
if(firstVisibleItem < 1 )
{
swipeRefreshLayout.setEnabled(true);
}else
{
swipeRefreshLayout.setEnabled(false);
}
totalItemCount = manager.getItemCount();
lastVisibleItem = manager.findLastVisibleItemPosition();
int visibleThreshold = 2;
if(isLoading == false)
{
if (totalItemCount <= lastVisibleItem + visibleThreshold) {
if(lobiAdapter.getItemCount() > 0)
{
if (lobiAdapter.getItemCount() < 5)
{
setIsLoaded();
}else{
// End has been reached
// Do something
PostListAPI postListAPI = new PostListAPI();
postListAPI.query.user_id = userId;
postListAPI.query.post_count = String.valueOf(counter);
postListAPI.query.flag = "load";
NewsFeedsAPIFunc newsFeedsAPIFunc = new NewsFeedsAPIFunc(BottomLobiFragment.this.getActivity());
newsFeedsAPIFunc.delegate = BottomLobiFragment.this;
setIsLoading();
newsFeedsAPIFunc.execute(postListAPI);
}
}
else {
setIsLoaded();
}
}
}
}
});