Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data from Cursor into ContextMenu

I want to get the current record of a cursor, instead of just the ID, so that I can manipulate a context menu.

I saw this example here that shows you how to get the ID:

 @Override
  public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case DELETE_ID:
        AdapterView.AdapterContextMenuInfo info=
          (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();

        delete(info.id);
        return(true);
    }

    return(super.onOptionsItemSelected(item));
  }

This is great because it allows me to get the appropriate SQLite database ID of the clicked context menu which will allow me to write a function to do a lookup. But surely I can just reuse the current cursor?

I tried doing this:

Cursor c = (Cursor) this.getListAdapter().getItem((int) info.id);
String itemPriority = c.getInt(1);  
Log.v(TAG, "Current item:" + itemPriority);

but the cursor line seems to return just the schema of the database instead of the record I'm after.

Could someone please shed some light.

EDIT: Thanks to @azgolfer I have found the solution. I use a fillData() method to populate the adaptor. Normally this is declared with no variables. I had to redefine this method with a field variable. The relevant part of the code to make the curstor adaptor visible in onContextItemSelected is here:

private void fillData() {
    Cursor itemsCursor = mDbHelper.fetchAllItemsFilter(mListId, mStatusFilter);
    startManagingCursor(itemsCursor);
    mItemAdaptor = new ItemAdapter(this, itemsCursor);
    this.setListAdapter(mItemAdaptor);      
}
like image 652
Eugene van der Merwe Avatar asked Jul 26 '12 18:07

Eugene van der Merwe


1 Answers

You are using a CursorAdapter to display your list items, right? Then you already have access to the cursor by calling getCursor() on the CursorAdapter itself. To retrieve the correct record from the cursor, you just need to get the position of the item user has pressed, then move the cursor to that position and retrieve your data.

First, determine the position of what the user pressed:

AdapterView.AdapterContextMenuInfo info=
      (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
int itemPosition = info.position; 

Then move the cursor to the desired position and retrieve the record:

Cursor cursor = (Your cursorAdapter).getCursor();
cursor.moveToPosition(itemPosition);
String itemPriority = cursor.getInt(1);  
Log.v(TAG, "Current item:" + itemPriority);
like image 107
azgolfer Avatar answered Nov 16 '22 20:11

azgolfer