tags:

views:

104

answers:

2

I've got a common use-case wherein a user selects one item out of many (say, on a spinner or autocomplete list), then enters the data. For example, let's say the user selects a country. Ultimately, the data I want is the country code, not the country name; but the users will want to select based on name, not code. To put it another way, user's will select "United States", but I ultimately want that to translate into "US".

There are a lot of countries. Is there an easy way to setup a mapping in Android to hash from the name to the code? I've thought of a few solutions, none of them are quite satisfactory in my mind:

  1. A database containing country/code, which I can query on.

  2. Setting up all countries as strings in strings.xml, then retrieving the resource by name.

  3. Creating a huge Map in code and using that. (This is the least satisfactory answer).

Anyone have any cleverer solutions?

A: 

How about storing it as a custom XML file in /res/xml that you read in when your app starts and load into a Map?

Something simple like:

<Map>
  <item key="us" value="United States">
  ...
</Map>
mbaird
Hmm, that's a good idea, but then I'd still need to write an XML parser just to pull this off (which seems like overkill for something so simple). Maybe if I settled on a simple name/value format, then I could apply the same parser to multiple files and save a lot of effort. Or maybe I could go with JSON instead of XML.
Daniel Lew
Yeah just keep it simple like what I added to my answer, and make it so you can use the same parser for multiple things. JSON or XML should work fine. JSON would take up less space I guess, which can be an issue if your file gets huge.
mbaird
+1  A: 

I usually go with 2 parallel string arrays declared like this in strings.xml:

<string-array name="country_codes">
    <item>us</item>
    <item>uk</item>
    <!-- ... -->
</string-array>

Then do

String[] countryCodes = getResources().getStringArray(R.array.country_codes);
alex
He needs a map, not an array. How would you map all those items in your string array to the display value?
mbaird
This is actually my favorite answer so far; what it lacks in internal consistency it makes up for in utility (because the string arrays can very easily be added to Spinners in XML). Still think there might be something better out there, though.
Daniel Lew