I have a list view, populated with several ListItems. I also have an Option Menu, which includes “Delete all items” button. When I hit this button, it calls for a method that deletes all items except the default and should also refresh the ListView.
This is the menu code:
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
...
case R.id.optMenuDeleteAllCategories:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to delete all categories?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
**deleteAllCategories();**
}
This is the deleteAllCategories() method:
public void deleteAllCategories()
{
manager.deleteAllCategories();
adapter.notifyDataSetChanged();
}
So it does delete everything, but the ListView doesn’t refresh. I have to quit the app and reopen it to see the change. I also tried to put the adapter.notifyDataSetChanged(); line right after calling for deleteAllCategories method, but the ListView still didn’t refresh.
So how can I refresh it without quitting the app?
Call adapter.clear() inside the deleteAllCategories method to also delete the items from the list.
Edit: The ArrayAdapter internally will work on different list instances then the one you passed in. So while changes to the objects inside your original list will be reflected, changes to the ArrayList you passed in will not be visible to the adapter.
You need to use the add, insert, remove and clear methods of the ArrayAdapter to modify the list in the adapter.