离开班级

时间:2016-01-21 17:23:06

标签: android json android-intent

我想从spinner下拉列表中选择countryName中的countryCode。这是我完成此代码后的代码我希望维护countryName和mCountryCode值并将其带到新活动以在JSON对象中使用它。我从locale对象获得了国家/地区代码,并将其放在arraylist国家/地区名称中以填充微调器。用户选择国家/地区名称后,我希望所选国家/地区名称再次成为国家/地区代码并将其存储在字符串值中。一切正常,直到破线。选择countryName是在字符串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;
                }
            }
        }

0 个答案:

没有答案