Bernard Bernard - 2 months ago 17
Android Question

Removing last item of a listview

It shows no error but the app crash when i click the button to remove the last item in the list view. List view works fine with the arraylist... just when i want to remove the last item, it gives me a crash.

btnUndo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int count = adapter.getCount();
adapter.remove(adapter.getItem(count));
adapter.notifyDataSetChanged();
}
});

Answer

Arrays are 0-based, so you should do the following:

adapter.remove(adapter.getItem(count - 1));

I also suggest to use notifyItemRemoved instead of notifyDataSetChanged.