简体   繁体   English

Android ListView刷新后重复旧数据

[英]Android ListView Repeating Old Data After Refresh

I have a Fragment page listing data in the listview from a json through a webservice. 我有一个片段页面,它通过网络服务从json列出listview中的数据。 I have a pull down <SwipeRefreshLayout> . 我有一个下拉<SwipeRefreshLayout> i use to swipe the fragment page to refresh the data which which will call the webservice again and load the data in listview. 我用来滑动片段页面以刷新数据,该数据将再次调用Web服务并将数据加载到listview中。

The code below does not empty the old data after refresh. 刷新后,下面的代码不会清空旧数据。 the data still remains in the listview and add the refreshed data to the listview below the old data. 数据仍保留在列表视图中,并将刷新的数据添加到旧数据下方的列表视图中。

to refresh method i call the service again 刷新方法,我再次致电服务

ArrayList<DataListItem> listMockData;
DataBaseAdapter HListAdapter;

swipeLayout.setOnRefreshListener(
            new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {

                    HListAdapter.clear();
                    listMockData.clear();
                    HListAdapter.notifyDataSetChanged();
                    requestWebService(currentPage);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            swipeLayout.setRefreshing(false);
                        }
                    }, 1000);
                }
            });

BaseAdapter BaseAdapter

public DataBaseAdapter(Context context, ArrayList<DataListItem> listData) {
    this.listData = listData;
    layoutInflater = LayoutInflater.from(context);
}

public void clear() {
    listData.clear();
}
@Override
public int getCount() {
    return listData.size();
}

@Override
public Object getItem(int position) {
    return listData.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}
public View getView(final int position, View convertView, ViewGroup parent)  
{
 newsItem = listData.get(position);
 if (convertView == null) {
        holder = new ViewHolder();
        convertView = layoutInflater.inflate(R.layout.home_post_list, null);
        holder.results = (LinearLayout) convertView.findViewById(R.id.results);
convertView.setTag(holder);

    } else {
        holder = (ViewHolder) convertView.getTag();
    }
holder.results.setText(newsItem.getResults());
 holder.position = position;
    return convertView;
}

 public static class ViewHolder {
 TextView results;
 }

Edit calling webservice 编辑呼叫网络服务

public void requestPosts(int pageId) {
    JSONObject pagedata = new JSONObject();
    try {
        pagedata.put("pageId", pageId);            
    } catch (JSONException e) {
        e.printStackTrace();
    }
    Volley.newRequestQueue(getActivity()).
    add(new JsonObjectRequest(com.android.volley.Request.Method.POST,
                url, pagedata
                , new com.android.volley.Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonArray) {
                if (jsonArray != null) {
                    try {
                        JSONObject allPost = new JSONObject(jsonArray.toString());
                        contacts = allPost.optJSONArray("GetPostListResult");
                        for (int i = 0; i < contacts.length(); i++) {
                            JSONObject c = contacts.getJSONObject(i);

                            String Result = c.getString("Result");

                            results[x] = Result;

                            x++;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else{
                    Log.e("ServiceHandler", "Couldn't get any data from the url");
                }
                listMockData = new ArrayList<HomeListItem>();
                DataListItem newsData = new DataListItem();
                newsData.setResult(results[i]);
                listMockData.add(newsData);

                dataToListView();
            }
        });
        }
        public void dataToListView(){

        listView = (ListView) root.findViewById(R.id.custom_list);
        HListAdapter = new DataBaseAdapter(getActivity(), listMockData);
        listView.setAdapter(HListAdapter);
        }

Try following code for public void onResponse(JSONObject jsonArray) 尝试使用以下代码来实现public void onResponse(JSONObject jsonArray)

if (jsonArray != null) {
        listMockData.clear();
        try {
            contacts = jsonArray.optJSONArray("GetPostListResult");
            for (int i = 0; i < contacts.length(); i++) {
                JSONObject c = contacts.getJSONObject(i);

                String result = c.getString("Result");
                if(result != null) {
                    DataListItem newsData = new DataListItem();
                    newsData.setResult(result);

                    listMockData.add(newsData);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } else{
        Log.e("ServiceHandler", "Couldn't get any data from the url");
    }
    HListAdapter.notifyDataSetChanged();
}

My guess is that you somewhere forgot to reset an Array or a counter variable or both. 我的猜测是您忘记了重置数组或计数器变量或两者都重置。 ( result and x ) resultx

EDIT : Try to set the adapter only once, for initialization. 编辑 :尝试仅将适配器设置一次,以进行初始化。 I changed the code a bit. 我稍微修改了代码。 Try to clear only the assigned data set listMockData , not the adapter. 尝试仅清除分配的数据集listMockData ,而不清除适配器。 Make sure, the returned JSON does not contain the duplicate data. 确保返回的JSON不包含重复数据。 dataToListView() should not be needed to refresh data. dataToListView()刷新数据。 Just clear listMockData , fill it with new values and then notifyDataSetChanged() . 只需清除listMockData ,用新值填充它,然后notifyDataSetChanged()

And another tip for the future: never upper case for the first letter for variable names in java. 未来的另一个技巧是:java中变量名的首字母永远不要大写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM