Search code examples
javaandroidarrayssubstring

Splitting a String for use in a UI selection element


I'm using this code to read some country names from a resource bundle and add them to a spinner:

String [] countries = this.getResources().getStringArray(R.array.CountryCodes);
ArrayAdapter<String> adapter =  new ArrayAdapter<String>(
    this, android.R.layout.simple_spinner_item, countries
);
adapter.setDropDownViewResource(
    android.R.layout.simple_spinner_dropdown_item
);
mCountries.setAdapter(adapter);

The resource data is XML that looks like:

<string-array name="CountryCodes" >
 <item>93,AF, Afganistan</item>
 <item>355,AL, Albania</item>
 <item>213,DZ, Algeria</item>
</string-array>

How can I display only the country names in the Spinner and then display the corresponding digits in a separate Edittext widget?

I know I have to use the split() method to remove the ",". But once I have an individual string element, like "93,AF, Afganistan", how do I get just the country name "Afganistan"? How do I keep that name in sync with the corresponding digits?


Solution

  • this will do using split mycoutries will have just the countries and myotherstuff the rest of the data from the line

    String[] mycountries= new String[countries.length];
    String[] myotherstuff = new String[countries.length];
     for(int i = 0; i < countries.length; i++) {
        String s = countries[i];
        String[] parts = s.split(","); 
        myotherstuff[i] = parts[0]+","+parts[1];
        mycountries[i] = parts[2];
    }