I am trying to remove all the elements from my RecyclerView
in my onRestart
method so the items don't get loaded twice:
@Override
protected void onRestart() {
super.onRestart();
// first clear the recycler view so items are not populated twice
for (int i = 0; i < recyclerAdapter.getSize(); i++) {
recyclerAdapter.delete(i);
}
// then reload the data
PostCall doPostCall = new PostCall(); // my AsyncTask...
doPostCall.execute();
}
But for some reason the delete
method I created in the adapter
is not functioning properly:
in RecyclerAdapter.java:
public void delete(int position){
myList.remove(position);
notifyItemRemoved(position);
}
public int getSize(){
return myList.size();
}
I think every other item in my list gets deleted instead of the entire list.
With a listview
it was so easy and I simply called adapter.clear()
.
Can someone please help me fix up the code?
I think I should be using notifyItemRangeRemoved(...,...);
but I am not sure how. TIA
Avoid deleting your items in a for loop and calling notifyDataSetChanged in every iteration. Instead just call the clear method in your list myList.clear();
and then notify your adapter
public void clearData() {
myList.clear(); // clear list
mAdapter.notifyDataSetChanged(); // let your adapter know about the changes and reload view.
}