views:

318

answers:

1

Hi,

I have created a list view that displays the names and dates of items stored in a SQLite database, now I want to use a Context Menu to modify these items stored in the database such as edit the name, delete, and view.

This is the code for the list view:

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview);

    SQLiteDatabase myDB = null; 
    myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null);

    Cursor cur = myDB.rawQuery("SELECT _id, trackname, tracktime" + " FROM " + MY_DB_TABLE, null);
    ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.listview, cur,
    new String[] { Constants.TRACK_NAME, Constants.TRACK_TIME}, new int[] { R.id.text1, R.id.text2});
    ListView list = (ListView)findViewById(R.id.list);
    list.setAdapter(adapter);
    registerForContextMenu(list);
}

and the Context Menu...

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle("Track Options"); menu.add(0, CHANGE_NAME, 0, "Change name");

    menu.add(0, VIEW_TRACK, 0, "View track");

    menu.add(0, SEND_TRACK, 0, "Send track");

    menu.add(0, DELETE_TRACK, 0, "Delete track");


}

I have used a Switch statement to control the menu items..

public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()){ case CHANGE_NAME: changename(); return true;

   case DELETE_TRACK:
       deletetrack();
       return true;

   default:
   return super.onContextItemSelected(item);

}

So how would I go ahead and map the deletetrack(); method to find the ID of the track stored in the database to the item that has been selected in the list view?

+1  A: 

in your onContextItemSelected(), do something like this:

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = 
        (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();

            Track track = (Track)mAdapter.getItem(info.position);

The key is "position", which will give you the index of the item selected.

synic
Or, since this is a `CursorAdapter`, the `id` value from the `info` object will give you the `_ID` of the row in the database. See http://github.com/commonsguy/cw-android/tree/master/Database/Constants/ for a sample project demonstrating deleting based off of a context menu.
CommonsWare
Oh cool - I didn't know about that one.
synic
Great example CommonsWare! Thank you very much!
LordSnoutimus