I want to sustain countryCode from selected countryName from a spinner dropdown list. This is my code after completing this code I want to sustain countryName and mCountryCode value and take it to new activity to use it in JSON object. I have got country code from locale object and put it in an arraylist country name to populate the spinner. After user selects country name I want that selected country name to be country code again and store it in a string value. All works fine till break line. Selected countryName is there in string countryCode is also there but after I leave the class mCountryCode value is not there.
I think variable scope is something I need to work on...
public class MyActivity extends AppCompatActivity{
String mCountryCode;
onCreate{
final String[] isoCountryCodes = Locale.getISOCountries();
//filling spinner object with countryName array using isoCountryCodes array
countryName.add("Select A country");
for (String countryCode : isoCountryCodes) {
Locale locale = new Locale("", countryCode);
countryName.add(locale.getDisplayCountry());
}
//spinner object has been set with array adapter and that works fine below is how to
//handle selected countryName and convert it to countryCode again and sustain its value
//in a string variable so along with countryName, the corresponding countryCode can be sent via JSON object...
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mCountryName = mSpinner.getSelectedItem().toString();
Locale locale;
for (String candidate : isoCountryCodes) {
locale = new Locale("", candidate);
if (locale.getDisplayCountry().equals(mSpinner.getSelectedItem())) {
mCountryCode = candidate;
break;
}
}
}