tags:

views:

1126

answers:

3

Here's the scenario: I have a ListActivity, and long-pressing on an item brings up a context menu. One item in the context menu is "delete", and that brings up a confirmation box (and AlertDialog). When the user presses OK in the confirmation dialog, I need to know the ID of the item that was originally selected, so that I can actually delete it.

The flow looks like this:


      This event:             Causes Android to call:
-----------------------------------------------------  
Long press an item        ->  onCreateContextMenu()
Select context menu item  ->  onContextItemSelected()
call showDialog()         ->  onPrepareDialog()
user clicks OK            ->  onClick()

In onCreateContextMenu and onContextMenuSelected, I can get at the id of the selected item from the ContextMenuInfo. In onPrepareDialog, however, I no longer have access to that information. The rub is that onPrepareDialog needs this information to set up an onClick listener on its POSITIVE button.

I know that, during onContextMenuSelected, I can stash the selected item's ID away into a field of my activity. I have done that, and it works. But it's also really ugly. The statefulness that it introduces makes me uneasy. Has anybody else seen a better way to pass such information around than to use fields in the activity?

+1  A: 

Since you only have one user who can only make one long keypress at a time in your application (if I understood the documentation right), why would storing the id in a field of your own be bad? Sounds like a perfectly reasonable way to do it.

kigurai
Agreed... it's ugly, but it'll work.
fiXedd
It forces me to make assumptions about how Android will call into my Activity. I think the order that I outlined in my question is correct, but I may have missed some nuance, and it might change in the future at Google's whim. Writing stateless code is preferable to writing very stateful code.
Daniel Yankowsky
A: 

You might want to consider storing the information in Preferences. They are a good way to store more persistent information. By checking what in the preferences on your onCreate/onResume/onRestart you can figure out where to resume your application.

http://developer.android.com/guide/topics/data/data-storage.html

Will
I only need to store this information for about 2 seconds (between when the user presses Delete and when they press OK). Preferences seem better for long-term storage.
Daniel Yankowsky
A: 

I see that, in Android 2.2 (API level 8), they added an overload to showDialog that takes a bundle. It looks like you could use put the selected item's ID in that bundle, which is then accessible in onPrepareDialog. This is exactly what I was looking for. Unfortunately, my device is stuck on 1.6 (API level 4).

Daniel Yankowsky