user1756209
user1756209

Reputation: 575

How to retrieve an ID in onContextItemSelected()

I need the ID from an item in onContextItemSelected(). I use the following code:

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    if (v.getId()==R.id.listView1) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
        menu.setHeaderTitle("Optionen");
        menu.add(Menu.NONE, info.position, 0, "Artikel entfernen");
    }
}

@Override
public boolean onContextItemSelected(MenuItem item) {       
    final ListView lv = (ListView)findViewById(R.id.listView1);
    Toast.makeText(getApplicationContext(), lv.getItemAtPosition(item.getItemId()).toString(), Toast.LENGTH_LONG).show();
    return true;
}

The info.position var could not be read from onContextItemSelected with item.getItemId! The app crashed with the log: String empty. Can you find a mistake? Thanks!

UPDATE I changed the code to:

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
    ContextMenuInfo menuInfo) {
    if (v.getId()==R.id.listView1) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
    menu.setHeaderTitle("Optionen");
    menu.add(Menu.NONE, info.position, 0, "delete post");
  }
}

@Override
public boolean onContextItemSelected(MenuItem item) {

  final ListView lv = (ListView)findViewById(R.id.listView1);
  //lv.getItemAtPosition(0).toString()


  AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();


  Toast.makeText(getApplicationContext(), info.position, Toast.LENGTH_LONG).show();
  //Toast.makeText(getApplicationContext(), lv.getItemAtPosition(item.getItemId()).toString(), Toast.LENGTH_LONG).show();


  return true;
}

But also this code doesn't work (NotFoundException). I have a listview (R.id.listView1) with items. If the user clicks on an item long, the context menu appears. There is the option "delete post". Then I need the ID from the post to delete it!

Are there other solutions?

UPDATE 2 I solved the problem:

Toast.makeText(getApplicationContext(), lv.getItemAtPosition(info.position).toString(), Toast.LENGTH_LONG).show();

Upvotes: 2

Views: 2786

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006674

info.id will be the id value associated with the given item in the AdapterView.

To get at info in onContextItemSelected(), use:

AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();

Also, note that context menus are becoming much less popular, in favor of action modes (a.k.a., contextual action bars) with an action bar.

Upvotes: 2

Related Questions