Search code examples
androidlistviewdelete-row

android: removing item from listview is not working properly


I have custom adapter with two textviews and one button, which should delete that row.

public class ListViewAdapter extends ArrayAdapter<OneRowListView> implements OnClickListener {
private ArrayList<OneRowListView> items;
private ContactsActivity ca;
private int position;
private OneRowListView o;

public ListViewAdapter(Context context, int textViewResourceId, ArrayList<OneRowListView> items) {
    super(context, textViewResourceId, items);
    this.items = items;
    ca = (ContactsActivity) context;
}   
@Override
public View getView(int pos, View convertView, ViewGroup parent) {
        View v = convertView;
        position = pos;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)ca.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.one_item_contacts_list, null);
        }
        o = items.get(position);
        if (o != null) {
                TextView name = (TextView) v.findViewById(R.id.name);
                TextView surname = (TextView) v.findViewById(R.id.surname);
                TextView phoneNumber = (TextView) v.findViewById(R.id.phonenumber);
                Button deleteButton = (Button) v.findViewById(R.id.deleteButton);
                deleteButton.setOnClickListener(this);
        // ...
        }
        return v;
 }

@Override
public void onClick(View v) {
    switch(v.getId()){
    case R.id.deleteButton:
        remove(items.remove(position));
        notifyDataSetChanged();
        break;
    }       
}
 }

problem is, when any button is pressed, it always removes last row, not the current one. Variable position always points at last row. Where is the problem ?


Solution

  • The problem is that when you do position = pos; you keep overriding the 'position' variable (since getView() gets called for each row while you are scrolling your ListView).

    As a quick fix, instead of using the 'position' variable, you could store in your deleteButton a tag that contains the row position. For example something like this, in your getView() method:

    deleteButton.setTag(pos);
    

    Then in your onClick() method you can do:

    int position = (int) v.getTag();
    ...