I have an error in this piece of code where I have declared public class variable mCountryCode as String.
for (mCountryCode : isoCountryCodes) {
locale = new Locale("", mCountryCode);
if(locale.getDisplayCountry().equals(mSpinner.getSelectedItem())) {
mCountryCode = locale.getCountry();
break;
}
}
If I use for (String mCountryCode : isoCountryCodes)
instead then the error will go away but I am not able to sustain the mCountryCode
string value after break;
line.
Yup, the enhanced for statement just doesn't work like that. It always declares a new variable.
You can use:
for (String tmp : isoCountryCodes) {
mCountryCode = tmp;
...
}
... although frankly that's a pretty odd thing to do. It seems to me that you don't really want to assign every value to mCountryCode
, but only the matching one:
for (String candidate : isoCountryCodes) {
Locale locale = new Locale("", candidate);
if (locale.getDisplayCountry().equals(mSpinner.getSelectedItem())) {
mCountryCode = candidate;
break;
}
}
Note that this doesn't assign to an existing locale
variable, but declares a new one in each iteration. That's almost certainly a better idea... you can always assign to a field in the if
statement if you need to.
See more on this question at Stackoverflow