我想從選定的國家/地區名稱中的國家/地區代碼中保留國家/地區代碼。這是我完成這段代碼後的代碼,我想維護countryName和mCountryCode的值,並將它帶到新的活動中,以便在JSON對象中使用它。我已經從locale對象獲取了國家/地區代碼,並將其置於arraylist國家/地區名稱中以填充微調器。用戶選擇國家/地區名稱後,我希望將所選國家/地區名稱再次作爲國家代碼,並將其存儲在字符串值中。所有的工作正常,直到斷線。選擇的國家/地區名稱在字符串countryCode中也存在,但在離開類mCountryCode後,該值不存在。離開課程後無法維持字符串變量的值
我覺得變量的作用域是我需要工作...
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;
}
}
}
您使用的是調用新的活動使用intent.putExtra(「keyCountry」,mCountryCode) –
tried..it不工作...即使在選擇國家後,mCountryCode變量中也會給出空值......中斷後值爲null;行 –