1

I'm making a network call and I fetch from server 50 items which I display on the RecyclerView. If user keeps scrolling I fetch 50 more (using a page_num = 2, 3, etc...) and it keeps going like that with 50 items every time.

So let's say that currently there are being displayed 150 items to the user . What I'm doing is :

    // This call is inside my `Fragment` class
    for (NotificationsServiceResponseNestedItem item: notificationsList){
        if (!dataset.contains(item)) {
            adapter.addItem(item);
        }
    }

// this call is inside my `Adapter` class
public void addItem(NotificationsServiceResponseNestedItem item) {
    dataset.add(item);
    notifyItemInserted(dataset.size() - 1);
}

If user scrolled so there are 150 items in my adapter that means the above loop executed 3 times. I also keep the dataset both in my Fragment and in my Adapter class ( but that's something not related with my question - I just pointed out so there are no any misconceptions )

Now if user stays in this screen I keep calling the server every X secs, so I keep getting the same 50 items ( loop does not runs at all since if condition is not true and everythings is OK ). Sometimes there are a couple of new items so let's say from the 50 items I get from server : 48 already exist and are being displayed in my RecyclerView and two of them are new - so I should add them to adapter and display them.

The problem is : notifyItemInserted(dataset.size() - 1); cause instead of adding the items at the first two positions, it adds them to the two last positions! Which is obviously wrong.

I've been looking at it the last couple of hours, but can't find an easy fix for that. Any ideas ?

Mes
  • 1,671
  • 3
  • 20
  • 36
  • `dataset.add(item); adapter.addItem(item);` you are adding the item twice – njzk2 Apr 14 '17 at 19:24
  • Yes I know, the first dataset is local in my screen (`Fragment`) and I needed for something else not relative to my question. The dataset which works with my adapter is the one stored inside my adapter class. Hope I explained it well - or just forget the first `dataset.add(item);` – Mes Apr 14 '17 at 19:26
  • @njzk2 I also removed it from my question so there are no any problems - like I said its a different `dataset` and I need it for something else. :) – Mes Apr 14 '17 at 19:28
  • you have to call `notifyItemInserted` on the position where you actually insert the items. If you add the items in your list, you should know where you are inserting them – njzk2 Apr 14 '17 at 19:35

0 Answers0