2016-01-21 17 views
1

我想從選定的國家/地區名稱中的國家/地區代碼中保留國家/地區代碼。這是我完成這段代碼後的代碼,我想維護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; 
       } 
      } 
     } 
+1

您使用的是調用新的活動使用intent.putExtra(「keyCountry」,mCountryCode) –

+0

tried..it不工作...即使在選擇國家後,mCountryCode變量中也會給出空值......中斷後值爲null;行 –

回答

-1

請求 如果有人認爲這應該是一個評論,而不是答案,請不要downvote,我可以不要將評論添加爲聲譽低的初學者。

答: 的問題是,你正在使用相同的名稱(mCountryCode)爲兩個不同的變量,一次是作爲一個全局變量,然後作爲for循環的局部變量。您在「break」之前分配的值實際上是分配給局部變量而不是全局變量。

解決方法是隻更改for循環中的局部變量的名稱。下面的代碼段爲「for循環」應該工作:

Locale locale; 
for (String countryCode : isoCountryCodes) { 
locale = new Locale("", countryCode);         
    if(locale.getDisplayCountry().equals(mSpinner.getSelectedItem())){ 
     mCountryCode = locale.getCountry(); 
     break; 
    } 
} 
意圖下
+0

不知道爲什麼我被拒絕投票:( – aquadeep

+0

我已經用創建新的var for循環替換了新的代碼並將其分配給mcountrycode ..仍然是相同的結果... –