Android List view refresh

vivek_Android picture vivek_Android · Nov 3, 2010 · Viewed 62.9k times · Source

I have one ListView which is showing me some data through an array (which is in another class and I'm accessing it through it's object).

Whenever I delete an element from the ListView through context menu, the list is not refreshing but the element is deleted from the array. How can I refresh the list to show this?

Code:

     public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    if (v.getId()==R.id.mainListView) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
        post=info.position;
      menu.setHeaderTitle(stocks[info.position]);
        String[] menuItems = stt;
        for (int i = 0; i<menuItems.length; i++) {
            menu.add(Menu.NONE, i, i, menuItems[i]);
            }
    }
  }

     @Override
      public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        int menuItemIndex = item.getItemId();
        String[] menuItems = stt;
        String menuItemName = menuItems[menuItemIndex];
        listItemName = stocks[info.position];
        stockname.remove(post-1);

    return true;
  }

Answer

blindstuff picture blindstuff · Nov 3, 2010

You have to notify your ListView adapter that the data has changed.

listViewAdapater.notifyDataSetChanged();

If that for some reason doesn't work and there are some wierd situations where it seems like it wasn't notifying, you can just reassign your adapter via the constructor with the updated array.