programing

RecyclerView 어댑터로 데이터를 업데이트하는 가장 좋은 방법

nasanasas 2020. 10. 29. 08:12
반응형

RecyclerView 어댑터로 데이터를 업데이트하는 가장 좋은 방법


이 질문에 이미 답변이 있습니다.

ListView 와 함께 클래식 어댑터를 사용해야 할 때 다음과 같이 ListView의 데이터를 업데이트합니다.

myAdapter.swapArray(data);

public swapArray(List<Data> data) {
  clear();
  addAll(data);
  notifyDataSetChanged();
}

RecyclerView 의 모범 사례가 무엇인지 알고 싶습니다 . A의 때문에 RecyclerView의 어댑터 당신은 할 수 없습니다 clearaddAll같이 ListView에 .

그래서 나는으로 시도했지만 notifyDataSetChanged작동하지 않았습니다. 그런 다음 내 관점에서 swapAdapter로 시도했습니다.

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);

그러나이 마지막 솔루션을 사용하여 여전히 어댑터의 새 인스턴스를 만들어야하며 이것이 최상의 솔루션이 아니라고 생각합니다. 새 .NET없이 내 데이터를 변경할 수 있어야합니다 MyRecyclerAdapter.


RecyclerView의 어댑터에는 ListView의 어댑터에서 사용할 수있는 많은 메서드가 제공되지 않습니다. 그러나 스왑은 다음과 같이 아주 간단하게 구현할 수 있습니다.

class MyRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
   List<Data> data;
   ...

    public void swap(ArrayList<Data> datas)
    {
        data.clear();
        data.addAll(datas);
        notifyDataSetChanged();     
    }
}

또한 차이점이 있습니다

list.clear();
list.add(data);

list = newList;

첫 번째는 동일한 목록 객체를 재사용하는 것입니다. 다른 하나는 목록을 역 참조하고 참조하는 것입니다. 더 이상 도달 할 수없는 이전 목록 개체는 가비지 수집되지만 먼저 힙 메모리를 쌓지 않으면 아닙니다. 이는 데이터를 교환 할 때마다 새 어댑터를 초기화하는 것과 동일합니다.


@inmyth의 대답은 정확합니다. 코드를 약간 수정하여 빈 목록을 처리하십시오.

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();
    }

Retrofit의 onResponse () 사용에서 목록을 가져 오기 위해 Retrofit을 사용하고 있습니다.

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

참고URL : https://stackoverflow.com/questions/30053610/best-way-to-update-data-with-a-recyclerview-adapter

반응형