Search code examples
androidandroid-listviewarraylisthashmapsimpleadapter

How to remove a value from a ArrayList<HashMap<String,String>> and from a ListView row in android?


I have generated a ListView using a SimpleAdapter. I have a button named remove on each row of my ListView. I want to remove or delete the item that is set on that row as well as from the items ( which is of the type Arraylist<Hashmap<String,String>> when I click the remove button. I have done the following coding but it doesn't help. Can anyone guide me step by step what to do? My codes are as below:

     //here items is of the type  ArrayList<HashMap<String,String>>


 ListAdapter k = new SimpleAdapter(cart_activity.this, items,
                                        R.layout.cart_list_view_items, new String[] {"Category","Details","quantity","images","Currency","Price","item_id"}, new int[] { R.id.cat_name_cart,
                                        R.id.cart_details,R.id.cart_qty,R.id.image_url,R.id.cart_currency,R.id.cart_price,R.id.cart_item_id}) {

            @Override
            public View getView(final int position, View convertView, ViewGroup parent) {
                // TODO Auto-generated method stub
                final View v = super.getView(position, convertView, parent);
                Log.i("arraylist position in cart activity and position",""+items.get(position).get("item_id")+"  "+position);
                Button remove=(Button)v.findViewById(R.id.remove);

remove.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        items.remove(position);
                    }
                });

    return v;
            }

        };

        salad_list.setAdapter(k);

Solution

  • Try this..

    1) Remove .clear() from ArrayList because it'll clear all details from ArrayList

    2) Then add notifyDataSetChanged() that will refresh your ListView.

    items.remove(position);
    k.notifyDataSetChanged();