Sangeetha Pinto
Sangeetha Pinto

Reputation: 1022

Recyclerview.notifyItemInserted() duplicates the list item

I have a requirement, where I should download the ad item while scrolling and update the list. Since calling notifyDatasetChnaged(), resets everything, I'm calling notifyItemInserted(position). But, calling this duplicated the items in the list. I found that there are no repeated items in the list. But after calling notifyItemInserted, it duplicates the item. I'm not getting how to resolve this issue. This what I'm doing:

mNewsList.add(mPreviousAdPosition, newsItem);
mAdapter.notifyItemInserted(mPreviousAdPosition);

If I call, it works properly, there are no repeated items. But I don't want my list items to recreate. What can be the issue ?

Upvotes: 3

Views: 3488

Answers (5)

Aditi
Aditi

Reputation: 389

You can add the object at the end of the array with each object having a position along with it where it needs to be shown in the recycler view. Sort this array on the basis of position before calling notifyItemInserted(position). In this way only required data will be drawn.I have recenlty followed this approach and works very well with dynamic sections added in between in recycler view.

Upvotes: 1

sfigo
sfigo

Reputation: 61

You code should be written like this:

  public class RecyclerViewAdapter extends RecyclerView.Adapter{

   ...

   public void addData(int position, Item newsItem) {

        mNewsList.add(position, newsItem);

        notifyItemInserted(position);

   }

   ...

 }

and then you need to call the fun addData

Upvotes: 0

Casablancais
Casablancais

Reputation: 243

I had the same problem for exactly the same use case, the solution is:

Implement this method in your Adapter :

@Override
public long getItemId(int position) {
    //Return the stable ID for the item at position
    return items.get(position).getId();
}

Call this method in the Constructor of your Adapter :

//Indicates whether each item in the data set can be represented with a unique identifier
setHasStableIds(true);

Upvotes: 4

PEHLAJ
PEHLAJ

Reputation: 10136

Create a temporary list and add items as mentioned below:

List<YourModel> mTmpList = new ArrayList<YourMdel>();

//add items (from 0 -> mPreviousAdPosition) to mTmpList;
for(int i=0; i<mPreviousAdPosition; i++) {
    mTmpList.add(mNewsList.get(i));
}

//add item at mPreviousAdPosition
mTmpList.add(newsItem);

//add remaining items and set i<=mNewsList.size() because we ha
for(int i=mPreviousAdPosition; i<=mNewsList.size(); i++) {
    mTmpList.add(mNewsList.get(i - 1)); //because we have added item at mPreviousAdPosition;
}

mNewsList = mTmpList;
mAdapter.notifyDataSetChanged();

Upvotes: 0

Dishonered
Dishonered

Reputation: 8861

You should add the item at the end of the list.

mNewsList.add(newsItem);

and then notify like this.

mAdapter.notifyItemInserted(mNewsList.size()-1);

Upvotes: 0

Related Questions