Home » Android » java – How do I delete an item from my custom base adapter?

java – How do I delete an item from my custom base adapter?

Posted by: admin June 15, 2020 Leave a comment


I am extending BaseAdapter to make a custom listview row. I have context menu that opens everytime a user holds on the row and prompts if he wants to delete it. However how do I remove the row? The hashmap is only test data.

private MyListAdapter myListAdapter;
private ArrayList<HashMap<String, String>> items;

public void onCreate(Bundle savedInstanceState) {

    items = new ArrayList<HashMap<String,String>>();
    HashMap<String, String> map1 = new HashMap<String, String>();
    map1.put("date", "10/09/2011");
    map1.put("distance", "309 km");
    map1.put("duration", "1t 45min");

    myListAdapter = new MyListAdapter(this, items);

private class MyListAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<HashMap<String, String>> items;

    public MyListAdapter(Context context, ArrayList<HashMap<String, String>> items) {
        this.context = context;
        this.items = items;

    public int getCount() {
        return items.size();

    public Object getItem(int position) {
        return items.get(position);

    public long getItemId(int position) {
        return position;

    public View getView(int position, View convertView, ViewGroup parent) {

        View view = convertView;

        if (view == null) {
            LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = layoutInflater.inflate(R.layout.row_log, null);

        TextView rowLogOverview = (TextView) view.findViewById(R.id.rowLogOverview);

        HashMap<String, String> item = items.get(position);

        return view;
How to&Answers:

You do not delete from the adapter ! You delete from the items ! and the adapter is between your items and the view. From the view you can get the position and according the position you can delete items. Then the adapter will refresh you views.

That means you need to do something like this



To delete, you’ll need to do 2 things:

  1. Call .remove() on your ArrayList (items).
  2. Call .notifyDataSetChanged() on the instance of your MyListAdapter class (mListAdapter).


  1. remove item from items
  2. call BaseAdapter.notifyDataSetChanged(). Then listview will be redrawn and target row will be removed from screen.


You should add a Listener on your adapter to handle the delete event.

public YourAdapter(Context context, List<T> rows, View.OnClickListener deleteListener) 
{ ... }

And on your getView() method set the listener


You can add a value on the btn tag to identifiy the current row :


Finally, on your Activity, your listener will fire with the current position in tag. You can then use the previous answer to update your adapter and refresh your listview.