如何在Swipe Refresh布局中获取数据



我正在回收器视图中从服务器获取数据。我正在尝试实现Swipe Refresh,以获取服务器上的更新数据。但是,当我刷新时,它会从服务器中获取最新数据,但在回收器视图中没有替换旧数据,因此我在recycler视图中具有重复的数据,既旧数据又有最新数据。averime i recresh data cop of recycler view

此我的代码下面:

fragment_home.xml

<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".Home"
android:orientation="vertical"
android:id="@+id/linearHome"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="8dp"
android:paddingBottom="16dp">  
 <android.support.v4.widget.SwipeRefreshLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/refresh">
    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/recycle"
        android:layout_marginTop="10dp"
        />
    </android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>

home.java

public class Home extends Fragment {
RecyclerView recycle;
ArrayList<LoadHomeBooks> list;
SwipeRefreshLayout refresh;
private static final String URL = "https://www.example.com"
public Home() {
    // Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_home, container, false);
    recycle = view.findViewById(R.id.recycle);
    refresh = view.findViewById(R.id.refresh);
    list = new ArrayList<>();
    recycle.setHasFixedSize(true);
    recycle.setLayoutManager(new LinearLayoutManager(getActivity()));
    loadData();
    refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
           loadData();
        }
    }); 
    return view;
  } 
} 
 private void loadData(){
     OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(22, TimeUnit.SECONDS)
                .readTimeout(22, TimeUnit.SECONDS)
                .writeTimeout(22, TimeUnit.SECONDS)
                .build();
        RequestBody formBody = new FormBody.Builder().add("city", myValue).build();
        Request request = new Request.Builder().url(URL).post(formBody).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (getActivity() != null) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                prog.setVisibility(View.GONE);
                                JSONArray jsonArray = new JSONArray(response.body().string());
                                if (jsonArray.length() == 0) {
                                    nobook.setVisibility(View.VISIBLE);
                                }
                                for (int i = jsonArray.length() - 1; i > -1; i--) {
                                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                                    String str1 = jsonObject.getString("Book_name");
                                    LoadHomeBooks model = new LoadHomeBooks(str1);
                                    list.add(model);
                                }
                               HomeBookAdapter adapter = new HomeBookAdapter(listist, getContext());
                                recycle.setAdapter(adapter);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
            @Override
            public void onFailure(Call call, final IOException e) {
                if (getActivity() != null) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            TastyToast.makeText(getActivity(), e.getMessage(), TastyToast.LENGTH_LONG, TastyToast.ERROR).show();
                        }
                    });
                }
            }
        });
 }

有人请让我知道我做错了什么。

谢谢

将您的setonRefreshlistener更改为:

refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
               list.clear();
               loadData();
            }
        }); 

这是更新或清除/重置回收视图的最佳方法,请在适配器中实现以下方法

public void updateData(List<LoadHomeBooks> listNew, int flag) {
        if (flag == 0) { //append
            for (int i = 0; i < listNew.size(); i++) {
                yourListInAddapter.add(listNew.get(i));
                notifyItemInserted(getItemCount());
            }
            //notifyDataSetChanged();
        } else { //clear all
            yourListInAddapter.clear();
            notifyDataSetChanged();
        }
    }

当您需要清除/重置回收查看时,请致电此

yourAddapter.updateData(null, 1);

当您需要附加项目以回收查看时,请致电此

yourAddapter.updateData(newList, 0);

为此使用diffutlis。在适配器中添加此功能。

fun receive(l: ArrayList<DaoModel>) {
    val result = DiffUtil.calculateDiff(MyDiffUtils(listOfItems, l))
    listOfItems.clear()
    listOfItems.addAll(l)
    result.dispatchUpdatesTo(this)
}

和onswiperefreshlistener称此方法

adapter.receive(list)

这是diffutils

class MyDiffUtils(private val oldList: MutableList<DaoModel>, private val newList: List<DaoModel>) :
DiffUtil.Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
    return oldList[oldItemPosition].Id == newList[newItemPosition].Id
}
override fun getOldListSize(): Int {
    return oldList.size
}
override fun getNewListSize(): Int {
    return newList.size
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
    return oldList[oldItemPosition] == newList[newItemPosition]
}}

最新更新