0

I am still learning Java. I have this XML string-array list:

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

I am using an Arrayadapter to add this array to a spinner like this:

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);

This works just fine, no problems with the XML, but what I really want to do is to display only the country in the spinner and then display the corresponding digits in a separate Edittext .

I know I have to use the split() method to remove the ",". but once I have the individual string element (example "93,AF, Afganistan")

How do I

  1. get just the country name
  2. keep the country name in sync with the corresponding digits
Kelly S. French
  • 11,967
  • 10
  • 60
  • 92
KingBryan
  • 361
  • 4
  • 17
  • @Simon Not a duplicate, as the xml parsing is done by android as a resource, and the String[] is already present. – njzk2 Feb 20 '14 at 21:46
  • @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. – KingBryan Feb 21 '14 at 06:38
  • @njzk2 Hmm, I thought I'd added a comment. My point is that 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
  • 15,923
  • 10
  • 34
  • 38
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