使用 swipeRefreshLayout 更新自定义适配器中的数据

update data in custom adapter using swipeRefreshLayout

我正在尝试使用 swipeRefreshLayout 更新数据,但每次向下滑动刷新时它都会重复旧数据而不是显示新数据。

你能帮我解决这个问题并告诉我我在哪里犯了错误以及如何改正它吗?

我在片段中的代码:

public class StoriesFragment extends Fragment {

    private static final String TAG = MainActivity.class.getSimpleName();

    private static final String url = "http://sho3a3.net/storiesfeed.json";

    private ProgressDialog pDialog;
    private List<StoriesItem> storiesListItem = new ArrayList<StoriesItem>();
    private ListView storiesListView;
    private CustomListAdapter adapter;

    private SwipeRefreshLayout swipeRefreshLayout;

    public StoriesFragment() {
        // 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.stories_fragment, container, false);

        /*Swipe Refresh Layout*/

        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                adapter.notifyDataSetChanged();
                getDataFromUrl();
            }

        });
        swipeRefreshLayout.setColorScheme(
                android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);


        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);

                getDataFromUrl();
            }
        });

        storiesListView = (ListView) view.findViewById(R.id.list);
        adapter = new CustomListAdapter(getActivity(), storiesListItem);
        storiesListView.setAdapter(adapter);

        /*Click Feed Item */
        storiesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(getActivity(), " " + i, Toast.LENGTH_SHORT).show();

                Object o = storiesListView.getItemAtPosition(i);
                StoriesItem storiesItem = (StoriesItem) o;
                Intent intent = new Intent(getActivity(), DetailsActivity.class);
                intent.putExtra("storiesItem", storiesItem);
                startActivity(intent);

            }
        });

        return view;
    }

    private void getDataFromUrl() {

        // RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        // Creating volley request obj
        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        //hidePDialog();

                        String title;
                        String date;
                        String profession;
                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                StoriesItem storiesItem = new StoriesItem();

                                //Title
                                title = obj.getString("title");
                                byte[] bytesTitle = title.getBytes("ISO-8859-1");
                                String stringTitle = new String(bytesTitle, "UTF-8");
                                storiesItem.setTitle(stringTitle);

                                //Date
                                date = obj.getString("date");
                                byte[] bytesDate = date.getBytes("ISO-8859-1");
                                String stringDate = new String(bytesDate, "UTF-8");
                                storiesItem.setDate(stringDate);


                                //Profession
                                profession = obj.getString("profession");
                                byte[] bytesProfession = profession.getBytes("ISO-8859-1");
                                String stringProfession = new String(bytesProfession, "UTF-8");
                                storiesItem.setProfession(stringProfession);


                                storiesItem.setThumbnailUrl(obj.getString("image"));
                                storiesItem.setContent(obj.getString("content"));


                                // adding movie to movies array
                                storiesListItem.add(storiesItem);


                            } catch (JSONException e) {
                                e.printStackTrace();
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }

                        }

                        // swipeRefreshLayout.setRefreshing(false);
                        onItemsLoadComplete();
                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data


                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getActivity(), "Error Connection", Toast.LENGTH_SHORT).show();
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                swipeRefreshLayout.setRefreshing(false);
                //hidePDialog();

            }
        });

        //requestQueue.add(movieReq);
        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);
    }

    void onItemsLoadComplete() {
        // Update the adapter and notify data set changed
        // ...
        adapter.notifyDataSetChanged();
        // Stop refresh animation
        swipeRefreshLayout.setRefreshing(false);
    }

    public void onUpdate() {
        adapter = new CustomListAdapter(getActivity(), storiesListItem);
        storiesListView.setAdapter(adapter);
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }
}

您的 getDataFromUrl 所做的只是从服务器获取一些数据并将它们添加到 storiesListItem 中。这样做,storiesListItem 中的先前项目将不会神奇地消失 :-) .

你应该做的是在每次刷新之前清楚列表:

swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                adapter.notifyDataSetChanged();
             storiesListItem.clear();
                getDataFromUrl();
 }

而不是:

swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    adapter.notifyDataSetChanged();
                    getDataFromUrl();
     }

我建议您宁愿在解析另一组 JSON 而不是 onRefresh() 之前清除列表,这样列表在刷新时仍会保留在后台。像这样:

String title;
String date;
String profession;

if(response.length() > 0) {
    // CLear list here
    storiesListItem.clear();

    // Parsing json
    for (int i = 0; i < response.length(); i++) {
        try {