Sunday, October 2, 2011

Deleting An Item From a ListActivity

One of the features in the Connexions for Android app is the ability to save modules, collections, lenses or searches to a list of Favorites.  The Favorites are stored in a SQLite database on the user's phone and displayed on the Favorites tab.  A long click on an item in the list displays a menu with a Delete option.

To remove an item from the Favorites list, two obvious things must happen:
  1. Remove the item from the database. 
  2. Remove the item from the display.
Originally, I wrote code to delete the selected favorite from the database and then refreshed the list from the database.  The performance was poor to say the least, but it worked.  Later, I came up with a better solution. 
The Favorites are displayed by the ViewFavsActivity class which uses the LensListAdaper class.  LensListAdapter extends the Android ArrayAdapter class and has an Array of Content objects.   The ViewFavsActivity calls MenuHandler.handleContextMenu() which deletes the selected item from the database. Here is a code snip where the item is deleted.

...
case R.id.delete_from__favs:
       context.getContentResolver().delete(Favs.CONTENT_URI, "_id="+ currentContent.getId(), null);
       return true;
...

To remove the item from the display, ArrayAdapter.remove() is called from ViewFavsActivity.  ArrayAdapter.remove() takes an Object as a parameter so I pass in the selected Content object.

public boolean onContextItemSelected(MenuItem item) 
{
          AdapterContextMenuInfo info= (AdapterContextMenuInfo) item.getMenuInfo();
          Content content = (Content)getListView().getItemAtPosition(info.position);
          MenuHandler mh = new MenuHandler();
          boolean returnVal = mh.handleContextMenu(item, this, content);
          if(item.getItemId() == R.id.delete_from__favs)
          {
              //readDB();
              adapter.remove(content);
          }
          if(returnVal)
          {
              return returnVal;
          }
          else
          {
              return super.onContextItemSelected(item);
          }
}

Using the remove() method tremendously improved the performance.

You can browse the source or download a zip file of the source. Connexions for Android is available in the Android Market or from the Connexions website.