1

I have a value resource file(i.e. under values in Android Studio). Below is the code :

<resources>
    <string-array name="countrycaptital">
        <item name="NewDelhi">India</item>
        <item name="Japan">Tokiyo</item>
        <item name="US">Washington</item>
<resources>

Please guide me to retrieve the country and its capital in my code from this XML data file(in Android).

  • Possible duplicate of [Android - reference a string in a string array resource with xml](http://stackoverflow.com/questions/4161256/android-reference-a-string-in-a-string-array-resource-with-xml) – Yatin Feb 11 '16 at 17:15

1 Answers1

0

You could do this:

String[] CountryCaptital = context.getResources().getStringArray(R.array.countrycaptital);   

Then access it as you would any java array. (note the misspelling of "country capital" in your naming...)

EDIT:

Sorry - I didn't realize you were trying to reference the attribute of an item. That is not possible. From the docs:

<item>

A string, which can include styling tags. The value can be a reference to another string resource. Must be a child of a element. Beware that you must escape apostrophes and quotation marks. See Formatting and Styling, below, for information about to properly style and format your strings.

No attributes.

http://developer.android.com/guide/topics/resources/string-resource.html

You could create two separate string arrays of the same length and use one as the key to the other when creating a HashMap, for example.

EDIT:

Two arrays like this:

<resources>
    <string-array name="capital">
        <item >New Delhi</item>
        <item >Tokyo</item>
        <item >Washington</item>
<resources>

and:

<resources>
    <string-array name="country">
        <item >India</item>
        <item >Japan</item>
        <item >US</item>
<resources>

String[] country = context.getResources().getStringArray(R.array.country);   
String[] capital = context.getResources().getStringArray(R.array.capital);   

Then create a HashMap and use a for loop to populate it.

Jim
  • 10,172
  • 1
  • 27
  • 36
  • Oops! Sorry about the misspelling...but this code snippet only returns me the names of countries(i.e. values in the XML file) and not the capitals which are the attributes... :-( – Abhishek Kumar Feb 11 '16 at 17:23
  • and sorry I misunderstood your question! Please see me edit. – Jim Feb 11 '16 at 17:46
  • Thanks Jim...very helpful...and would be great if you could suggest me any other way of organizing my XML data and then retrieving the attribute value... – Abhishek Kumar Feb 11 '16 at 17:55
  • See my edit.. I think that should get you where you need to go. – Jim Feb 11 '16 at 18:09