I’m trying to save a spinner’s selection to a shared preference, but I’m having trouble getting it to save. I have no problem saving text, but the spinner seems to be a bit more difficult. I’m using a Preference Connector that I found online that seems to work well for text, so that might be part of the problem. Here’s a brief section of code that includes only the hair color selector spinner. I think my problem arises when I try to read the SP (readPerson()), but I’m not entirely sure. If you have any suggestions, please let me know. Thanks!
public class PreferencesActivity extends Activity {
Spinner hairSpinner; //hair color selector
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_profile);
init();
}
private void init() {
hairSpinner = (Spinner) findViewById(R.id.hair_spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.hair_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
hairSpinner.setAdapter(adapter);
}
public void save(View view) {
int hairText = hairSpinner.getSelectedItemPosition();
if (hairText != 100)
PreferenceConnector.writeInteger(this, PreferenceConnector.HAIR,
hairText);
}
private void readPerson() {
hairSpinner.setSelection(getText(PreferenceConnector.readInteger(this,
PreferenceConnector.HAIR, 0)));
}
}
This is the part that I found online (a section of it):
public class PreferenceConnector{
public static final String PREF_NAME = "PEOPLE_PREFERENCES";
public static final int MODE = Context.MODE_PRIVATE;
public static final String HAIR = "HAIR";
public static void writeInteger(Context context, String key, int value) {
getEditor(context).putInt(key, value).commit();
}
public static int readInteger(Context context, String key, int defValue) {
return getPreferences(context).getInt(key, defValue);
}
public static void writeString(Context context, String key, String value) {
getEditor(context).putString(key, value).commit();
}
public static String readString(Context context, String key, String defValue) {
return getPreferences(context).getString(key, defValue);
}
}
Everything looks fine except for the “getText”, what is it doing exactly? I’m guessing setSelection is looking for an int but getText is converting it to a String or something.