Search code examples
androidandroid-asynctaskandroid-5.0-lollipopandroid-cardview

RecycleView/CardView data set update


I am currently trying to update a RecyclerView once an AsyncTask has completed its operation.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Initializing RecycleView
    mRecyclerView = (RecyclerView)findViewById(R.id.list);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());

    mAdapter = new AdvertAdapter(this.results, R.layout.card_advert, this);
    mRecyclerView.setAdapter(mAdapter);

Here is a code snippet from my AsyncTask:

    @Override
    protected void onPostExecute(String result){
        // your stuff
        listener.onTaskCompleted(data);
    }

In the listener Activity class, I am updating the data set and attempting to notify my custom adapter that the data set has been changed:

@Override
public void onTaskCompleted(ArrayList<Data>results) {
    this.results = results;
    this.mAdapter.notifyDataSetChanged();
    System.out.println("Done.");
}

It seems that notifyDataSetChanged() is not actually doing anything, as the list remains empty even after the final line. From the debugger, I can verify that results does contain the correct results, and the onTaskCompleted is being run on the main thread. How can I update my RecyclerView with the new results?


Solution

  • I think you should add the ArrayList<Data>results to your adapter data.

    Something like this:

    @Override
    public void onTaskCompleted(ArrayList<Data>results) {
        //this.results = results;
    
        this.mAdapter.clear();
        this.mAdapter.add(results);
        //or this.mAdapter.results = results;
    
        this.mAdapter.notifyDataSetChanged();
        System.out.println("Done.");
    }