1

My AsyncTaskLoader is loading data from a remote server. When new data arrives, naturally a call is made to onLoadFinished. At this point I don't know how to give the new data to the RecyclerView.Adapter. Calling notifyDataSetChanged does not give it the new data: it simply tells it there is new data. So any advice on how I might do this? Right now the best I can think of is to create my own setData method in my implementation of RecyclerView.Adapter as

public void setData(List<MyObject> data){
    if(null != data && !data.isEmpty()){
      synchronized(mItems){
        mItems.clear();
        mItems.addAll(data);
      }
      notifyDataSetChanged();
    }
  }

Is my idea the best there is? Or is there a more sound way of doing this?

learner
  • 11,490
  • 26
  • 97
  • 169
  • 1
    I personally do like this too. I put a method to update my data into my adapter and then call notifyDataSetChanged. – xiaomi Sep 06 '15 at 01:56
  • 1
    Same as well even in the BaseAdapter days, I go with this route on changing the underlying dataset and just invoke notifyDataSetChanged(). – deubaka Sep 06 '15 at 01:58

3 Answers3

1

Expose a public method in your adapter to update data.

For example, you could put it like this

public void updateItems(ArrayList<MyObject> myObjects) {
     this.data = myObjects;
     notifyDataSetChanged();
}
0

You have two options, 1. Re- instantiate your adapter with your new data and reset the adapter. 2. The way you do it.

I can not think of any other methods.

diyoda_
  • 5,274
  • 8
  • 57
  • 89
0

Ok, I had the same issue and here is the solution what I did. 1st I passed list object from onLoadFinished and in the RecyclerViewAdapter I have created method name setCardInfoList() and there I passed this object to global List object which I define in adapter class.

In onLoadFinished method..

@Override
public void onLoadFinished(android.content.Loader<List<Earthquake>> loader, List<Earthquake> earthquakes) {

    if (earthquakes != null && !earthquakes.isEmpty()) {

        adapter.setCardInfoList(earthquakes);
        adapter.notifyDataSetChanged();
    }else {
        emptyView.setText("No Earthquake Found...");
    }

}

Inside Adapter class

public void setCardInfoList(List<Earthquake> earthquakes){
    this.earthquakeList = earthquakes;
}
patel dhruval
  • 1,002
  • 10
  • 12