Remove all items from RecyclerView - android

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

This works great for me:
public void clear() {
int size = data.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
data.remove(0);
}
notifyItemRangeRemoved(0, size);
}
}
Source: https://github.com/mikepenz/LollipopShowcase/blob/master/app/src/main/java/com/mikepenz/lollipopshowcase/adapter/ApplicationAdapter.java
or:
public void clear() {
int size = data.size();
data.clear();
notifyItemRangeRemoved(0, size);
}
For you:
#Override
protected void onRestart() {
super.onRestart();
// first clear the recycler view so items are not populated twice
recyclerAdapter.clear();
// then reload the data
PostCall doPostCall = new PostCall(); // my AsyncTask...
doPostCall.execute();
}

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.
}

setAdapter(null);
Useful if RecycleView have different views type

recyclerView.removeAllViewsInLayout();
The above line would help you remove all views from the layout.
For you:
#Override
protected void onRestart() {
super.onRestart();
recyclerView.removeAllViewsInLayout(); //removes all the views
//then reload the data
PostCall doPostCall = new PostCall(); //my AsyncTask...
doPostCall.execute();
}

This is how I cleared my recyclerview and added new items to it with animation:
mList.clear();
mAdapter.notifyDataSetChanged();
mSwipeRefreshLayout.setRefreshing(false);
//reset adapter with empty array list (it did the trick animation)
mAdapter = new MyAdapter(context, mList);
recyclerView.setAdapter(mAdapter);
mList.addAll(newList);
mAdapter.notifyDataSetChanged();

Help yourself:
public void clearAdapter() {
arrayNull.clear();
notifyDataSetChanged();
}

I use this. This actually clears the recylerview completely. I had tried adapter.notifyDataSetChanged(); but it was just not updating any view in my case. Of course U had cleared the list first. But below code works fine and clears view of recyclerview completely.
listName.clear(); // clear list
adapter = new ModelAdaptor(Activity.this, listName);
recyclerView.setAdapter(adapter);

Another way to clear the recycleview items is to instanciate a new empty adapter.
mRecyclerView.setAdapter(new MyAdapter(this, new ArrayList<MyDataSet>()));
It's probably not the most optimized solution but it's working like a charm.

ListView uses clear().
But, if you're just doing it for RecyclerView. First you have to clear your RecyclerView.Adapter with notifyItemRangeRemoved(0,size)
Then, only you recyclerView.removeAllViewsInLayout().

For my case adding an empty list did the job.
List<Object> data = new ArrayList<>();
adapter.setData(data);
adapter.notifyDataSetChanged();

private void clearRecyclerView() {
CustomListViewValuesArr.clear();
customRecyclerViewAdapter.notifyDataSetChanged();
}
use this func

On Xamarin.Android, It works for me and need change layout
var layout = recyclerView.GetLayoutManager() as GridLayoutManager;
layout.SpanCount = GetItemPerRow(Context);
recyclerView.SetAdapter(null);
recyclerView.SetAdapter(adapter); //reset

You have better clear the array-list that you used for recyleview adapter.
arraylist.clear();

public void clearData() {
mylist.removeAll(mylist);
mAdapter.notifyDataSetChanged();
recyclerView.setAdapter(mAdapter);
}

Related

How to update recyclerview the simplest way using notifyDataSetChanged

I'm trying to update my recyclerview using notifyDataSetChanged() but it doesn't work. I am setting the adapter to the recyclerview like this:
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(ctx, LinearLayoutManager.VERTICAL, false);
lstSong.setLayoutManager(mLayoutManager);
lstSong.setItemAnimator(new DefaultItemAnimator());
lstSong.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(0), true));
arrSong = new ArrayList<Song>();
arrSong = kFunc.getAllSong();
songAdapter = new SongAdapter(ctx, arrSong);
lstSong.setAdapter(songAdapter);
This lines of code displays the data. But when i add a new data and refresh the recyclerview with songAdapter.notifyDataSetChanged(); the data won't show up. I know i can display it by using setAdapter() but i want to do it properly.
I add the data before I make the refresh. This is the code:
kFunc = new Function(ctx);
Song song = new Song();
song.setTitle(title);
song.setArtist(artist);
song.setYear_released(yearReleased);
song.setAlbum(album);
song.setGenre(genre);
song.setDuration(duration);
song.setCode(code);
song.setLyrics(lyrics);
kFunc.addSong(song);
dialog.dismiss();
arrSong = kFunc.getAllSong();
songAdapter.notifyDataSetChanged();
Create a method inside adapter like
public updateItems(ArrayList<Song> songs){
arrSong=songs;
}
And while getting new values in your class call the method using adapdter object
lstSong.updateItems(arrSong);
notifyDataSetChanged();
I don't know where you added new item to RecyclerView.Adapter. This is a sample code to add and set a item. More detail Sample RecyclerViewAdapter
#Override
public void addItem(M item) {
items.add(item);
notifyItemInserted(items.size() - 1);
}
#Override
public void addItem(int position, M item) {
items.add(position, item);
notifyItemInserted(position);
}
#Override
public void addAllItems(List<M> items) {
this.items.addAll(items);
notifyDataSetChanged();
}
#Override
public void setItems(List<M> items) {
this.items = items;
notifyDataSetChanged();
}
You should try by updating the list of the songs before you notify the adapter.
for example
arraySongs = <retrive updated data of the song>;
adapter.notifyDataStateChanged()
if you are in ListView which you are not but for you information only.
adapter.lstSong =<updated songs List>;
adapter.notifyDataStteChanged();
try this this worked for me.
happy coding. :)

How to reset recyclerView position item views to original state after refreshing adapter

I have a RecyclerView with rows that have views that when clicked will be disabled for that row position.
The problem is after I update the adapter like this:
adapterData.clear();
adapterData.addAll(refreshedAdapterData);
notifyDataSetChanged();
After refreshing the data, the disabled views at the previous recycler position still remain disabled even though the data is refreshed.
How can I reset the views to the original state after refreshing adapter data.
Use below code.
adapterData.clear();
adapterData.addAll(refreshedAdapterData);
adapter.notifyDataSetChanged();
OR
recyclerView.invalidate();
When you call notifyDataSetChanged(), the onBindViewHolder() method of every view is called. So you could add something like this in the onBindViewHolder() of your Adapter method:
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
if (refreshedAdapterData.get(position).isInDefaultState()) {
//set Default View Values
} else {
//the code you already have
}
}
I have resolved this by putting a conditional statement inside onBindViewHolder method instructing all positions to reset the disabled views if data meets the required conditions for a refreshed data.
#Christoph Mayr, thanks for your comments. It helped point me in the right direction.
I cleared the data then notify change but the selected checkbox doesn't reset but just moves up one position. Let say I selected item #1 , move out of the RecyclerView, came back and it will auto select item #0.
So, I created new adapter again at onResume(), i worked for me but i don't know if it's the right way to handle this situation.
#Override
public void onResume() {
super.onResume();
if(selectedItems != null && selectedItems.size() > 0){
selectedItems.clear(); // if no selected items before then no need to reset anything
if(adapter != null && recyclerView != null){
// to remove the checked box
adapter = null;
adapter = new MyAdapter(items, new MyAdapter.MyAdapterListener() {
#Override
public void onSelected(int pos) {
selectedItems.add(items.get(pos));
}
#Override
public void onUnSelected(int pos) {
selectedItems.remove(items.get(pos));
}
});
recyclerView.setAdapter(adapter);
}
}
}

Recyclerview not updating rows correctly when removing data from arraylist?

my RecyclerView contains Text and Delete Button when delete is clicked specific row will be deleted from ArrayList
pending.remove(p);// pending is arraylist
after this updating RecyclerView by calling this function which is inside Adapter
swap(pending);
public void swap(ArrayList<DownloadingActivity.scheduleListType> newList) {
if (pendingList != null) {
pendingList.clear();
pendingList.addAll(newList);
} else {
pendingList = newList;
}
notifyDataSetChanged();
}
but the problem is that correct item deleted successfully from ArrayList pending but on RecyclerView wrong update is displayed.
if i delete second item from array list pending but in RecyclerView updated
deleted item is last
when activity is reloaded then values in RecyclerView are showing correctly
searched lot of about it but did not found any way to solve
Instaead of using swap() to delete the item from your array list and adding them back into diffrent array list, I will suggest that you use notifyItemRemoved in your adapter. So, your adapter will look like below.
RecyclerViewAdapter.java :
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
DownloadingActivity.scheduleListType> p = pendingList.get(position);
//....
//....
holder.deleteBnt.setOnClickListner(new View.OnClickListener() {
#Override
public void onClick(View view) {
pendingList.remove(p);
notifyItemRemoved(position)
}
})
}

Empty Recycler view is not getting updated with new data

I intialize my recycler view adapter with an empty arraylist initially.
Then later once I fetch data from API I try to update the adapter by calling notifyDataSetChanged() but none of call back methods in my adapter is getting fired
void initRecyclerView()
{
myList = new ArrayList<>();
myRecyclerAdapter = new myRecyclerAdapter(getActivity(), myList, "");
myRecyclerView.setAdapter(myRecyclerAdapter);
linearLayoutManager = new LinearLayoutManager(getActivity());
myRecyclerView.setHasFixedSize(true);
myRecyclerView.setLayoutManager(linearLayoutManager);
}
After getting data from API I just update the adapter as follow :
void updateRecyclerView(ArrayList<Data> newList)
{
if (myList.isEmpty())
linearLayoutManager.removeAllViews();
myList.clear();
myList.addAll(newList);
myRecyclerAdapter.notifyDataSetChanged();
}
void updateRecyclerView(ArrayList<Data> newList)
{
//you don't have to removeviews
// if (myList.isEmpty())
// linearLayoutManager.removeAllViews();
myList.clear();
myList.addAll(newList);
myRecyclerAdapter.notifyDataSetChanged();
}
I made a costliest mistake and ponder around something else instead of looking it at different aspect.
I had SwipeRefreshLayout that wraps RecyclerView.
I should've just use setRefreshing(false) once data downloaded through API call. Instead I used setVisibility(VIEW.GONE) on mymSwipeRefreshLayout`.
This visibility change of SwipeRefreshLayout impacted RecyclerView within.
I hope none will do this mistake. Perhaps someone might come across this tiniest mistake so I Mark my answer as accepted answer.
First of all try to set layout manager and then set adapter to list :
void initRecyclerView()
{
linearLayoutManager = new LinearLayoutManager(getActivity());
myRecyclerView.setHasFixedSize(true);
myRecyclerView.setLayoutManager(linearLayoutManager);
myList = new ArrayList<>();
myRecyclerAdapter = new myRecyclerAdapter(getActivity(), myList, "");
myRecyclerView.setAdapter(myRecyclerAdapter);
}
Also pay attention that if you want to change data set or notify your adapter about the changes, you should do it in your main thread.
runOnUiThread(new Runnable() {
#Override
public void run() {
myList.clear();
myList.addAll(newList);
myRecyclerAdapter.notifyDataSetChanged();
}
});

recyclerView ClickListener return null after notifyDataSetChanged()

i am using a recyclerView and loading the data from database.The recyclerView item have 2 buttons. The recyclerView loads fine and clicks work fine for the following code.
allData=db.getCatData(CATEGORYLIST_CIDD,1);
textlistadapter = new TextListAdapter(getActivity(), allData);
recyclerView.setAdapter(textlistadapter);
later i rearrange the adapter data for displaying the data in descending order by using this code
db=new DatabaseHandler(getActivity().getApplicationContext());
allData=db.getCatData(CATEGORYLIST_CIDD,order_id);
textlistadapter = new TextListAdapter(getActivity(), allData);
recyclerView.setAdapter(textlistadapter);
textlistadapter.notifyDataSetChanged();
Now the items are rearranged on the recyclerView, but the onShareButtonClickListener returns null, here is the code of the adapter.
private OnShareButtonClickListener onShareButtonClickListener;
public interface OnShareButtonClickListener {
void onItemClick(View view, Pojo obj, int position);
}
public void setOnShareButtonClickListener(final OnShareButtonClickListener onShareButtonClickListener) {
this.onShareButtonClickListener = onShareButtonClickListener;
}
the click listener code is here
holder.bt_share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Snackbar.make(view, "Share Clicked", Snackbar.LENGTH_SHORT).show();
if (onShareButtonClickListener != null) {
onShareButtonClickListener.onItemClick(view, c, position);
}
}
});
The click does not work since the onShareButtonClickListener is null.
The same code works well for the first time and once i change the order then the click events are not working, all other functions are working well.
you should only need to do this once:
textlistadapter = new TextListAdapter(getActivity(), allData);
recyclerView.setAdapter(textlistadapter);
later on, if you want to update/change the data, then you should do something like this:
textlistadapter.setListItems(allData);
textlistadapter.notifyDataSetChanged();
Where setListItems() is a public method in your adapter, an example like this:
public void setListItems(List<> allData) {
this.data.clear();
this.data.addAll(allData);
}
It's easy to understand what you are doing wrong. You populate an array which will feed your adapter with data, that meaning that, after setting the adapter, if you want it's data to change, you only need to change the array you populated the data with, and notify the adapter for the data change.
For example:
myData = db.getData();
myAdapter = new MyAdapter(this,myData);
recyvlerview.setAdapter(myAdapter);
Now every time you want to change the data, you only need to change your myData and notifity the adapter
myAdapter.notifyDataSetChange();
Basically instead of doing this:
db=new DatabaseHandler(getActivity().getApplicationContext());
allData=db.getCatData(CATEGORYLIST_CIDD,order_id);
textlistadapter = new TextListAdapter(getActivity(), allData);
recyclerView.setAdapter(textlistadapter);
textlistadapter.notifyDataSetChanged();
This should suffice
db=new DatabaseHandler(getActivity().getApplicationContext());
allData=db.getCatData(CATEGORYLIST_CIDD,order_id);
textlistadapter.notifyDataSetChanged();

Categories

Resources