0

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
bibi_bryan
  • 371
  • 3
  • 17
  • @user28... : you need to split your strings using String.split(",") and use the item at position 2 (plus a trim). – njzk2 Feb 20 '14 at 21:49
  • @njzk2 thanks. That was very helpful. Now i understand BradR's answer. – bibi_bryan Feb 21 '14 at 06:38
  • Using any string methods on XML is doomed to failure. Use a parser instead then do the string ops on the parsed out data. Let's not start open the gates of hell again http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – Simon Feb 21 '14 at 09:50
  • @Simon: Yes, but this is really unrelated to XML. Android does all the parsing for you (`getResources().getStringArray`), and what the SO is really working on is an array of Strings, as you can see in BradR's answer. – njzk2 Feb 21 '14 at 14:34

2 Answers2

2

If you want to separate country name from the given array, you can use something like this.

    String[] edited = new String[countries.length];
    for(int i = 0; i < countries.length; i++) {
        String s = countries[i];
        edited[i] = s.substring(s.lastIndexOf(','));
    }
jimmy0251
  • 16,293
  • 10
  • 36
  • 39
1

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];
}
BradR
  • 593
  • 5
  • 16