如何根据首选项中的值设置微调器值

时间:2014-09-02 21:16:56

标签: android json spinner

我从jsonarray填充一个微调器,我需要将微调器设置为存储在首选项中的值。我想将微调器String“id”设置为与首选项中存储的“idlocatie”相等。

  SharedPreferences mySharedPreferences =PreferenceManager.getDefaultSharedPreferences(this);     
    final String locatie= mySharedPreferences.getString("idlocatie", "");
 JSONObject jsonLocatii = JSONfunctions.getJSONfromURL("http://www.mySite");
      try{      
    JSONArray  earthquakes = jsonLocatii.getJSONArray("earthquakes");

        for(int i=0;i<earthquakes.length();i++){                        
            JSONObject e = earthquakes.getJSONObject(i);                
            String id = e.getString(TAG_IDLOCATIE);
            String name = e.getString(TAG_LOCATIE);             
            locatiiList.add(new Locatii(id, name.toUpperCase()));        
            locatii = (Spinner) findViewById(R.id.spinLocatie);
            LocatiiAdapter cAdapter = new LocatiiAdapter(this, android.R.layout.simple_spinner_item, locatiiList);
            locatii.setAdapter(cAdapter);                 
        }   

 }catch(JSONException e)        {
     Log.e("log_tag", "Error parsing data "+e.toString());
 }

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您是否尝试设置所选值? 试试locatii.setSelection(cAdapter.getPosition(locatie));

或者您是否尝试更改与选择相关的实际值?

编辑:在这里试试吧。你需要进行一些健全性检查,但希望是正确的方向。 另一种选择是覆盖getPosition(),另一种选择是从locatiiList中找到索引并使用它。

SharedPreferences mySharedPreferences =PreferenceManager.getDefaultSharedPreferences(this);     
final String locatie= mySharedPreferences.getString("idlocatie", "");
JSONObject jsonLocatii = JSONfunctions.getJSONfromURL("http://www.mySite");
try {      
    JSONArray  earthquakes = jsonLocatii.getJSONArray("earthquakes");

    for(int i=0;i<earthquakes.length();i++){                        
        JSONObject e = earthquakes.getJSONObject(i);                
        String id = e.getString(TAG_IDLOCATIE);
        String name = e.getString(TAG_LOCATIE);             
        locatiiList.add(new Locatii(id, name.toUpperCase()));        
    }   
// Move these out of the for loop.
    locatii = (Spinner) findViewById(R.id.spinLocatie);
    LocatiiAdapter cAdapter = new LocatiiAdapter(this, android.R.layout.simple_spinner_item, locatiiList);
    locatii.setAdapter(cAdapter);                 

 } catch(JSONException e) {
     Log.e("log_tag", "Error parsing data "+e.toString());
 }

locatii.setSelection(getIndex(locatii, locatie));

private int getIndex(Spinner spinner, String myString) {
    for (int i=0;i<spinner.getCount();i++){
        if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(myString)){
            return i;
        }
    }
    // Check for this when you set the position.
    return -1;
}