views:

436

answers:

1

I'm writing an application and need some help with consistently storing and loading preferences related to certain resources. Let me give an example.

Suppose I have 10 spinners. They all have the same functionality but different meaning. Because they have the same functionality, I can bind them to the same onItemSelectedListener, which will then deal with the selected value.

Well, what if I also want to store the preferences for each spinner? For example, when a spinner value is selected, I'd store a key "spinner SOMETHING" = SOME_DATA.

The problem is - what should this SOMETHING be? The listener has the following signature:

public void onItemSelected(AdapterView parent, View v, int position, long id)

The position and id are not helpful here as they're set relative to each spinner.

However, the parent, which in this case is the spinner itself, should have all the information I need. I tried using parent.getId() to get a resource ID of each spinner and store the preference using a key "spinner ID" but apparently these resource IDs change when you add more resources into your app, so my settings would get reset because the keys change.

What should I do here? I can't seem to find a simple parent.getName() function of some sort that would return me a consistent name of each spinner.

Thank you.

+2  A: 

The getId is the only thing I know of that has a unique reference to the View, but as you say, a view might not have the same Id in the next build of your app.

The best human-readable identifier available out of the box would be getPrompt, which would simply show you whatever you have set as the spinners prompt. It should be an OK identifier, but it is of course also prone to breakage if you manually change your prompt texts.

The most break-proof way, then, is to specify an identifier in the general container - tag - that every View contains.

String myIdentifier = (String) parent.getTag();

If you're already using the tag for something else, the 1.6+ APIs include the ability to specify several tags, and access them via index. If you need to support older API versions, you could always set the tag to a wrapper object that contains both the identifier, and your original tag.

David Hedlund
Thank you - I think this is exactly what I was looking for.
Artem Russakovskii
Note that the index-based tags are primarily for use by reusable libraries or system code, not so much for applications, according to Romain Guy.
CommonsWare
thanks for the remark, commonsware. HTC keeps dragging out on the firmware updates, so i haven't moved on to playing much with the interesting sdk4 stuff yet myself =/
David Hedlund