user9609225
user9609225

Reputation:

recyclerview: notify item inserted messes up the whole list

I have a recyclerview initially with 5 items. Now What I want to do is to add another 5 items exactly at positions 0,1,2,3 and 4. So I do this:

         //add another 5 items to my recyclerview

         for(int i=0 , i < 5 , i++){
          //add new item to the list at the specified position
          my_list.add(i , "new item"+ String.valueOf(i));

          //notify adapter

          my_adapter.notifyItemInserted(i);

         }

The problem is that calling (notifyItemInserted(i)) messes up the whole list. But calling notifyAdapterDataSetChanged() doesnt mess up anything.

I want to avoid calling notifyAdapterDataSetChanged().

Why that happens?

Thanks.

EDIT

I will update the question so others understand the problem:

I have initially 5 items at 0,1,2,3,4 positions, now I want to add 5 new Items to the previous 5 items at 0,1,2,3,4 (I want the new ones to take the place of the previous ones) how to notify the adapter properly of this?

Upvotes: 3

Views: 11580

Answers (1)

Khemraj Sharma
Khemraj Sharma

Reputation: 59004

First i appreciate :) you to use method notifyItemInsert() because it will give you some inserting animation without any effort and will never hang up your view even hundreds of items in list when notifying. I have seen many developers using notifyDataSetChange that works well with small list. But if your api does not support paging and you got hundreds in list then your view will stuck for a while when setting adapter.

If you want change existing items.

for(int i=0 , i < 5 , i++){
  my_list.set(i , "new item"+ String.valueOf(i));
}

my_adapter.notifyItemRangeChanged(0, 5); 

You can also use notifyItemChanged(list.size() - 1); as below.

If you want insert new

for (int i = 0; i < 5; i++) {
            list.add("new item" + String.valueOf(i));
            notifyItemInserted(list.size() - 1);
        }

Now understand - first you dont know how many items are already in list, so dont use my_list.add(i , "new item"+ String.valueOf(i)); because this will replace old item, second use notifyItemInserted(list.size() - 1);, it will automatically check which item has been inserted.

You can also use notifyItemRangeInserted as by Hed. That is also correct

Update : You can do it like this. First add your 5 items list in existing list. Then set final list to adapter.

ArrayList arrayList5Items;
ArrayList arrayList = my_adapter.getList();
arrayList5Items.addAll(arrayList);
my_list = arrayList5Items;
my_adapter.notifyItemRangeInserted(0, 5);

Upvotes: 3

Related Questions