Using a Context Menu to delete from a SQLite database in Android

Posted by LordSnoutimus on Stack Overflow See other posts from Stack Overflow or by LordSnoutimus
Published on 2010-03-26T19:17:20Z Indexed on 2010/03/26 19:43 UTC
Read the original article Hit count: 261

Filed under:
|
|
|

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?

© Stack Overflow or respective owner

Related posts about android

Related posts about java