0

I looked at a lot of examples and managed to get this far, but i still can't get the button to delete the item from my array. How do i utilize remove(position) correctly?

public class adapter extends ArrayAdapter {

public adapter(Context context, ArrayList<User> users) {

    super(context, 0, users);
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {


    User user = getItem(position);

    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_main, parent, false);
    }

    TextView question = (TextView) convertView.findViewById(R.id.question);
    TextView answer = (TextView) convertView.findViewById(R.id.answer);

    question.setText(user.name);
    answer.setText(user.hometown);

    ImageButton remove = (ImageButton) convertView.findViewById(R.id.removeButton);

    remove.setTag(position);

    remove.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {


            notifyDataSetChanged();}
        });

    return convertView;


    }
}

User List

public class User {
public String name;
public String hometown;

public User(String name, String hometown) {
    this.name = name;
    this.hometown = hometown;
}

public static ArrayList<User> getUsers() {
    ArrayList<User> users = new ArrayList<>();
    users.add(new User("Hi", "hi"));
    users.add(new User("Marla", "San Francisco"));
    users.add(new User("Sarah", "San Marco"));
    return users;
}

}

Aure
  • 11
  • 3
  • 1
    where is your logcat??? – M D Dec 18 '14 at 09:11
  • I didn't keep the log, but after changing some stuff, I think it was due to using remove(position) incorrectly. How do i implement this correctly? – Aure Dec 18 '14 at 09:45

3 Answers3

0
  1. Assign position as a TAG to Button in GetView
  2. OnClick of Button, remove that position item from ArrayList
  3. To refresh ListView UI, call adapter.notifyDataSetChanged() method

This will help you, Delete a ListItem by clicking the ImageView within the ListItem

Community
  • 1
  • 1
Ganesh AB
  • 4,652
  • 2
  • 18
  • 29
0

You have ArrayList users

on the particular event remove the object for arrayList of users, and then call dapter.notifyDataSetChanged() method simply.

0
  1. Add this method in your adapter class.
    public void removeItem(int position){
    arrayList.remove(position);
    notifyDataSetChanged();
    }
  2. Call above method from onClick of Button like.
    remove.setOnClickListener(new
    View.OnClickListener(){
    @Override
    public void onClick(View view) { removeItem(position);}
    });
  3. The reference link : Listview delete item and Refresh - android
Community
  • 1
  • 1
Puneet Gupta
  • 101
  • 8