Skip to content Skip to sidebar Skip to footer

How Do I Set Spinner Value Based On The Value In Preferences

I populate a spinner from a jsonarray and i need to set the spinner to a value stored in preferences. I want to set the spinner String 'id' to be equal with 'idlocatie' stored in p

Solution 1:

if I understand it right, you're trying to set the selected value? try locatii.setSelection(cAdapter.getPosition(locatie));

Or are you trying to change an actual value associated with the selection?

EDIT: Here, try this. You'll need some sanity checking but hopefully on the right direction. Another option is to override getPosition(), and yet another is to find the index from locatiiList and use that.

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(newLocatii(id, name.toUpperCase()));        
    }   
// Move these out of the for loop.
    locatii = (Spinner) findViewById(R.id.spinLocatie);
    LocatiiAdapter cAdapter = newLocatiiAdapter(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;
}

Post a Comment for "How Do I Set Spinner Value Based On The Value In Preferences"