Recyclerview adapter initialised with empty array and subsequently populated with values

1.1k views Asked by At

I'm creating a recyclerview adapter in my onCreate method with an empty list. It is necessary to do so as tagging onto the mAdapter is a scroll listener which allows me to obtain another page from the database server if I scroll up (I have not copied and pasted that code for brevity sake).

public class MainActivity extends ActionBarActivity {

ArrayList<Post> totalPost = new ArrayList<>();

 @Override
 protected void onCreate(Bundle savedInstanceState) {
        mAdapter = new MyAdapter(totalPost, mRecyclerView);
        mRecyclerView.setAdapter(mAdapter); }

I'm calling my network operation in onResume and onResume happens subsequent to onCreate.

Once I get a success from my network operation, I'm doing this however nothing happens:

 totalPost = Lists.newArrayList(result.getPosts()); //saving the network results into an array
 mAdapter.notifyDataSetChanged();

I have also tried this:

totalPost = Lists.newArrayList(result.getPosts()); //saving the network results into an array
mAdapter.notifyItemRangeChanged(0, totalPost.size());

I have also tried this and it works but it is not ideal. I create a new adapter here and I also lose my scroll listener. I can also not reference my scroll listener in my method that references my network operations as that would be 'circular reference':

totalPost = Lists.newArrayList(result.getPosts()); //saving the network results into an array
mAdapter = new MyAdapter(totalPost, mRecyclerView);
mRecyclerView.setAdapter(mAdapter);

Why is the adapter not working?

2

There are 2 answers

2
McGuile On BEST ANSWER

I think your adapter isn't taking in the new values. Try creating a method defined in your adapter class and calling that method with the new values passed in. Like this:

totalPost = Lists.newArrayList(result.getPosts());
mAdapter.update(totalPost, mRecyclerView)

// Adapter Class

public void update(ArrayList<Post> totalP, RecyclerView recycler) {
    totalPost = totalP;
    mRecyclerView = recycler;
    this.notifyDataSetChanged();
0
Andre Classen On

You should extend your adapater , with a add function. After you created the adapter and assigned it to the recyclerview you should 'communicate' with the recyclerview through your adapter. Add something like this to your adapter. Where mItems is the internal backing array in your adapter.

public void addAll(int location, Collection<T> items) {
    mItems.addAll(location, items);
    notifyItemRangeInserted(location, items.size());
}

public void add(T item, int position) {
    mItems.add(position, item);
    notifyItemInserted(position);
}