Best way to update data with a RecyclerView adapter [duplicate] - android

This question already has answers here:
How to update RecyclerView Adapter Data
(16 answers)
Closed 5 years ago.
When I have to use a classic adapter with a ListView, I update my data in the ListView like this:
myAdapter.swapArray(data);
public swapArray(List<Data> data) {
clear();
addAll(data);
notifyDataSetChanged();
}
I would like to know what is the best practice for a RecyclerView. Because in a RecyclerView adapter you can't do a clear and addAll as in ListView.
So I tried just with a notifyDataSetChanged, but it didn't work.
Then I tried with a swapAdapter on my view:
List<Data> data = newData;
MyRecyclerAdapter adapter = new MyRecyclerAdapter(data);
// swapAdapter on my recyclerView (instead of a .setAdapter like with a classic listView).
recyclerViewList.swapAdapter(adapter, false);
But with this last solution, I still have to create a new instance of my adapter and I feel like it's not the best solution. I should be able just to change my data without a new MyRecyclerAdapter.

RecyclerView's Adapter doesn't come with many methods otherwise available in ListView's adapter. But your swap can be implemented quite simply as:
class MyRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
List<Data> data;
...
public void swap(ArrayList<Data> datas)
{
data.clear();
data.addAll(datas);
notifyDataSetChanged();
}
}
Also there is a difference between
list.clear();
list.add(data);
and
list = newList;
The first is reusing the same list object. The other is dereferencing and referencing the list. The old list object which can no longer be reached will be garbage collected but not without first piling up heap memory. This would be the same as initializing new adapter everytime you want to swap data.

#inmyth's answer is correct, just modify the code a bit, to handle empty list.
public class NewsAdapter extends RecyclerView.Adapter<...> {
...
private static List mFeedsList;
...
public void swap(List list){
if (mFeedsList != null) {
mFeedsList.clear();
mFeedsList.addAll(list);
}
else {
mFeedsList = list;
}
notifyDataSetChanged();
}
I am using Retrofit to fetch the list, on Retrofit's onResponse() use,
adapter.swap(feedList);

DiffUtil can the best choice for updating the data in the RecyclerView Adapter which you can find in the android framework. DiffUtil is a utility class that can calculate the difference between two lists and output a list of update operations that converts the first list into the second one.
Most of the time our list changes completely and we set new list to RecyclerView Adapter. And we call notifyDataSetChanged to update adapter. NotifyDataSetChanged is costly. DiffUtil class solves that problem now. It does its job perfectly!

Found following solution working for my similar problem:
private ExtendedHashMap mData = new ExtendedHashMap();
private String[] mKeys;
public void setNewData(ExtendedHashMap data) {
mData.putAll(data);
mKeys = data.keySet().toArray(new String[data.size()]);
notifyDataSetChanged();
}
Using the clear-command
mData.clear()
is not nessescary

Related

How to restore to the previous state in RecyclerView after loading more data

I have been working with RecyclerView for a while. I am following lazy loading, so I am showing 10 data on the view each time. If user scroll to the bottom, the page re-load from the TOP! however, I want to stay where it was previously! So, I have tried to use
recyclerView.scrollToPosition(position);
However, this breaks the UI flow!
My second try is using onSaveInstanceState() and onRestoreInstanceState(Bundle state); However, that does not work! My page is re-loads to the top!
Parcelable state = layoutManager.onSaveInstanceState();
layoutManager.onRestoreInstanceState(state);
I have tried every other methods, apparently none is working for me!
Any help would be highly appreciated! Thanks in advance!
Note : Make sure that you are not initialising or calling setAdapter() method each time after updating your dataset. If not, then
You have to update your data list and call notifyDataSetChanged() which will update your adapter from existing position.
Let's say you have stored your data into ArrayList mData;
Your getItemCount() would be
#Override
public int getItemCount() {
if (mData != null && mData.length() > 0)
return mData.size();
return 0;
}
Now create one more method in your adapter which you will called each time whenever you will get new data from server. This method will simply override your dataset and will update your adapter
private void updateDataSet(ArrayList<String> mData){
this.mData = mData;
notifyDataSetChanged();
}
I have done this functionality before 2 days ago
I share my idea with you
Make
Listview lv; //Assume Find view by Id
List<Model> models = new ArrayList();
Now Make an Adapter and assign blank models
CustomAdapter adapter = new CustomeAdapter(context,models);
lv.setAdapter(adapter);
Now when you have new data to load with lazylodaing
do this
models.addAll(newModels); //new ModelList
adapter.notifyDataSetChanged();
Thats it.
This is the default behaviour Recycler View to recycle/resuse views. As in official docs:
https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html
If you are having any view related issues then save your view state in your List<Object> like setting visible item or not per position. And in your onBindViewHolder method as per position show/hide your view.

Android: Recyclerview adapter inside recyclerview adapter. How to update data of inside recylcerview?

I got a recylcerview, which has another recylcerview as an element of it. However, i am confused how to update data of the inside recylcerview. How should I do it?
I don't know if this will work for you because i don't have your code, but you can create a updateAdapter , inside of it you must refresh everything.
For example we have 2 arrayList:
private void updateAdapter() {
this.mItems = c.getArray();
this.mItemsNr = c.getNr();
//and call notifyDataSetChanged
notifyDataSetChanged();
}
mItems and MItemsNr are 2 arrayList and c is an object where i have the 2 new arrayList.So i update the 2 arrayList and hten i call notifyDataSetChenged(); to update my adapter.
Hope this could help you.

Replace ArrayAdapter's dataset

In Android, you can provide an ArrayList when creating an ArrayAdapter for a ListView. I need to update a number of items in the ArrayList.
The ususal way is to just call notifyDatasetChanged. What I prefer to do is reload the entire data into a new ArrayList from my database and then apply this new ArrayList to the existing ArrayAdapter but without creating a new adapter. Creating a new adapter will cause the ListView to go blank and start with position zero. This would also be obvious if the user were scrolling and I suddenly recreated a new adapter.
Is it possible to apply a completely new ArrayList to the existing adapter? The primary reason I want to do this is because it is very fast to just reload a new ArrayList with all the data than having to go through an existing ArrayList and inserting, deleting or updating existing items.
1) First of all. You need to use custom ArrayAdapter (or SimpleAdapter or RecycleViewAdapter)
2) Than create function in your custom adapter :
// Initialize your list;
private ArrayList<Model> arrayList;
.....
//Create constructor and past starting ArrayList
public MyAdapter (ArrayList<Model> array) {
this.arrayList = array;
}
......
public void updateMyData (ArrayList array) {
clear();
// Or you can use arrayList.addAll(array); - just add new items
this.arrayList = array;
notifyDataSetChange();
}
.....
3) In your Activity (or where you initialize adapter)
just use code like this:
MyAdapter myAdapter = new MyAdapter(startArratListData);
// And Than for updating data:
myAdapter.updateMyData(newArrayListData);

Android RecyclerView infinity scrolling: how to add more items to dataset

I have implemented my RecyclerView and even added an onscrolllistener to support infinity scrolling and now I'm stuck with a, hopefully, easy problem: How can I add the newly loaded data to the existing dataset?
My current approach: I create a new array with the length of the existing dataset + the length of the newly loaded data. I System.arraycopy my existing dataset and add the new content with a for-loop.
This works but the list is always reset (scrolls back to the top) and I assume my way to add additional content is overly complicated/wrong, though the tutorials I have looked at seem to pass over this "detail".
Update: I'm currently calling "scrollToPosition" on the UI-Thead after the data has been loaded, but I doubt this is the correct way of doing this or am I wrong?
You shouldn't be adding stuff to your dataset, you will sooner or later run out of memory. What you can do is return a big number (I used Short.MAX_VALUE) item in getItemCount inside your adapter and in the method that requests a view for postion you should do position % list.size();
It is not a truly endless RecyclerView this way, but good enough. I will paste some code tomorrow, I don't have it here now :/
I think you have to add items inside your adapter. Let`s say
class Adapter extends Recycler.Adapter<Recycler.ViewHolder>{
List<YourCustomObject> list;
public Adapter(){
list = new ArrayList<>();
}
public void addItem(YourCustomObject item){
list.add(item);
notifyItemDateSetChanged(); //This method for adapter to notice that list size have been changed
}
// Here your views
}
There is implementation of Your fragment or Activity where you retrieve data from internet.Let` say
class MainActivity extends AppCompactActivity{
Adapter adapter = new Adapter();
List<YourCustomObjects> objects;
public void onCreateView(){
//////// Something yours
}
public void onLoadMore(){
///// Your operation to retrieve data and init it to your list objects
for(YourCustomObject object : objects){
adapter.addItem(object);
}
}
}

How to update a custom listview in android

I have an application developed to get all the third party applications installed and to display them on a list view! this is been done by an extended baseAdapter. In this list I do an uninstallation of a selected application using this code :
Intent intent = new Intent(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:" + Packname));
startActivity(intent);
Now what I want is to update the list view with the changed data so that the user can get updated application list. how can I achieve this. I found that notifyDatasetchanged method but it can only be used for simple listviews! what are the options that I have and please let me know of any tutorials to achieve my outcome!
thank you.
What do you mean only for simple listviews? How is yours different? You should be able to call notifyDataSetChanged on your custom adapter class after deleting one of your items. You can create a function to do it...
private ArrayList<Object> list;
public void deleteItem(int index){
list.remove(index);
notifyDataSetChanged();
}
you will have an adapter (something that extends BaseAdapter probably) that you set into the ListView using setAdapter(...). add a method to your adapter implementation class that sets the underlying objects that are backing the list. make sure to call notifyDataSetChanged() at the end. something like,
public class MyAdapter extends BaseAdapter<String> {
private List<String> strings;
...
void setModel(List<String> strings) {
this.strings = strings;
this.notifyDataSetChanged();
}
}
simply calling your adapter's setModel(...) will cause the ListView to update.

Categories

Resources