Spinner Selection - Save To Sharedpreferences, Then Retrieve
Solution 1:
You have to call editor.apply();
once after all of your editor.put();
statements. Otherwise all of the changes that you've made to the preferences will get discarded. Assuming that the items in your array won't be changing position at all then you can just store the selected position as an int in your preferences.
to Save:
int selectedPosition = yourSpinner.getSelectedItemPosition();
editor.putInt("spinnerSelection", selectedPosition);
editor.apply();
to Load:
yourSpinner.setSelection(prefs.getInt("spinnerSelection",0));
If the items in your array are going to change then you'll have to store the actual string, instead of the position. Something like this would work:
String selectedString = yourArray[yourSpinner.getSelectedItemPosition()];
editor.putString("spinnerSelection", selectedString);
editor.apply();
and
find the position of the string by looping through your array and checking array[i] against the value stored in prefs. Then call yourSpinner.setSelected(position)
. If you use an ArrayList instead this part could be done without the loop by calling
ArrayList.indexOf(prefs.getString("spinnerSelection", ""));
Be aware that only ArrayList does have an indexOf();
method. On a plain Array you can not use the indexOf();
method, you'll have to manually search your Array to find the right value.
Post a Comment for "Spinner Selection - Save To Sharedpreferences, Then Retrieve"