整个列表视图重复

时间:2016-06-28 10:46:54

标签: android listview

我有一个列表视图,显示来自Web服务的值。它加载listview时很好。但是,当我点击任何项目打开一个新片段(显示该项目的详细信息)并返回到相同的列表视图时,其项目每次都会翻倍。例如,如果我(原始)总共有5个项目。然后当我从片段返回时,总计数将是10,然后是15,依此类推。这意味着该应用程序一次又一次地添加所有项目。我搜索了解决方案并做了像adapter.notifyDataSetChanged()这样的通用解决方案,但它仍然是重复的。如果有人能告诉我这个问题,我将不胜感激。

public class CustomListAdapter extends ArrayAdapter<Model> {

    private Context mContext;
    int resource;
    private ArrayList<Model> mListData = new ArrayList<Model>();



    public CustomListAdapter(Context mContext, int resource, ArrayList<Model> mListData) {
        super(mContext, resource, mListData);
        this.resource = resource;
        this.mContext = mContext;
        this.mListData = mListData;
    }

    public void setListData(ArrayList<Model> mListData) {
        this.mListData = mListData;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return super.getCount();
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        View v = convertView;
        final ViewHolder holder;
        if (v == null) {
            holder = new ViewHolder();

            LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();

            v = inflater.inflate(resource, parent, false);

            holder.custname = (TextView) v.findViewById(R.id.cust_name);
            holder.date = (TextView) v.findViewById(R.id.date);
            holder.staffname = (TextView) v.findViewById(R.id.staff_name);
            holder.time = (TextView) v.findViewById(R.id.time);
            holder.service = (TextView) v.findViewById(R.id.service);
            holder.refid = (TextView) v.findViewById(R.id.refid);


            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }




        final Model item = mListData.get(position);

        holder.custname.setText(item.getCustname());
        holder.date.setText(item.getDate());
        holder.staffname.setText(item.getStaffname());
        holder.time.setText(item.getTime());
        holder.service.setText(item.getService());
        holder.refid.setText(item.getRefid());


        return v;
    }

    class ViewHolder {

        TextView custname, date, staffname, time, service, refid;
    }
}
public class ListFrag extends Fragment{

    private SwipeMenuListView listView;
    private CustomListAdapter adapter;
    private CShowProgress cShowProgress;
    private SQLiteHandler db;
    private String uid, bookingId;
    private ArrayList<Model> arrayList = new ArrayList<>();
    private static final String BOOKED_LIST = "http://192.168.220.13/android/showbookinglist";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.listfrag, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        listView = (SwipeMenuListView)view.findViewById(R.id.list);
        db = new SQLiteHandler(getActivity());
        cShowProgress = CShowProgress.getInstance();

        


        fetchDetails();

        adapter = new CustomListAdapter(getActivity(), R.layout.listitem, arrayList);
        listView.setAdapter(adapter);


        
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                String a = arrayList.get(i).getCustname();
                String b = arrayList.get(i).getStaffname();
                String c = arrayList.get(i).getService();
                String d = arrayList.get(i).getDate();
                String e = arrayList.get(i).getTime();
                String f = arrayList.get(i).getRefid();
                String g = arrayList.get(i).getEmail();
                String h = arrayList.get(i).getServprice();
                String j = arrayList.get(i).getSpeclprice();
                String k = arrayList.get(i).getStatus();


                db.addDetails(a, b, c, d, e, f, g, h, j, k);

                DetailsView details = new DetailsView();
                ((Bookings)getActivity()).replaceFragment(details);
            }
        });

       
    }

    private void fetchDetails() {

        cShowProgress.showProgress(getActivity());

        StringRequest stringRequest = new StringRequest(Request.Method.POST, BOOKED_LIST,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        cShowProgress.hideProgress();

                        try {
                            JSONArray jsonArray = new JSONArray(response);
                            for(int i=0; i<jsonArray.length(); i++){
                                JSONObject obj = jsonArray.getJSONObject(i);
                                Model model = new Model();
                                model.setCustname(obj.getString("customername"));
                                model.setDate(obj.getString("staffdate"));
                                model.setStaffname(obj.getString("staffname")+"(Staff)");
                                model.setTime(obj.getString("stafftime"));
                                model.setService(obj.getString("servicename"));
                                model.setRefid(obj.getString("booking_referenceid"));
                                model.setEmail(obj.getString("customeremail"));
                                model.setServprice(obj.getString("serviceprice"));
                                model.setSpeclprice(obj.getString("specialprice"));
                                model.setStatus(obj.getString("status"));
                                model.setBookid(obj.getString("bookingid"));

                                arrayList.add(model);
                            }

                            adapter.notifyDataSetChanged();






                        } catch (JSONException e) {
                            // JSON error
                            e.printStackTrace();
                            Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getActivity(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();

                params.put("spaid", "145");
                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);
    }

    

}

4 个答案:

答案 0 :(得分:2)

尝试将其更改为.. B&#39;因为您正在添加以前创建的列表中的元素。所以您必须清除它。

 private void fetchDetails() {

if(arrayList!=null )arrayList.clear(); // this line

        cShowProgress.showProgress(getActivity());

答案 1 :(得分:0)

问题是,当你回到片段时,它会被重新创建并再次调用 onViewCreated 。从那里再次调用 fetchDetails(),然后您将第二次将整个List添加到适配器。因此,您可以在 fetchDetails()之前清除列表,或者只是必须再次获取它们。

答案 2 :(得分:0)

通过以下方式更改onResponse方法的try-catch块。

       try {
                   JSONArray jsonArray = new JSONArray(response);

                   arrayList = new ArrayList<>();

                   for(int i=0; i<jsonArray.length(); i++)
                   {
                        JSONObject obj = jsonArray.getJSONObject(i);
                         Model model = new Model();
                            model.setCustname(obj.getString("customername"));
                            model.setDate(obj.getString("staffdate"));
                            model.setStaffname(obj.getString("staffname")+"(Staff)");
                            model.setTime(obj.getString("stafftime"));
                            model.setService(obj.getString("servicename"));
                            model.setRefid(obj.getString("booking_referenceid"));
                            model.setEmail(obj.getString("customeremail"));
                            model.setServprice(obj.getString("serviceprice"));
                            model.setSpeclprice(obj.getString("specialprice"));
                            model.setStatus(obj.getString("status"));
                            model.setBookid(obj.getString("bookingid"));

                            arrayList.add(model);
                        }

                        adapter.notifyDataSetChanged();

答案 3 :(得分:0)

这种情况正在发生,因为您没有清除arrayList。因此,每次构造数组和适配器时,都要将元素添加到已经包含元素的数组中。

这就是为什么你有5,然后是10,然后是15等等......

在添加新元素之前清除数组

arrayList.clear();

或者编制另一种策略,例如:

  • 每次返回片段时都不会填充数组。
  • 在将元素添加到数组之前检查元素是否存在。