Recyclerview.notifyItemInserted () duplicate list item

I have a requirement where I have to load the ad element while the list is scrolling and updating. Since the call notifyDatasetChnaged()

drops everything, I call notifyItemInserted(position)

. But, calling it, duplicating the items in the list. I found that there are no duplicate items in the list. But after the call notifyItemInserted

it duplicates the element. I don't understand how to solve this problem. This is what I am doing:

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

      

If I call it works correctly, there are no duplicate items. But I don't want my list items to be recreated. What could be the problem?

+3


source to share


5 answers


You can add an object to the end of the array with each object having a position with it where it should appear in the recycler view. Sort this array by position before calling notifyItemInserted(position)

. Thus, only the required data will be selected. I remember this approach and did a great job with dynamic sections added between them in recycler mode.



+1


source


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

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 adapter constructor:

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

      

+1


source


The 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 fun addData

0


source


Create a temporary list and add items as follows:

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();

      

0


source


You must add an item at the end of the list.

mNewsList.add(newsItem);

      

and then report it.

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

      

-1


source







All Articles