Reputation: 2731
I'm using shared preferences and am a bit unsure on what the best practice is on what data type to store key value pairs.
Example: I have a spinner with 3 drop down options: apple, banana, orange
In my spinner, I select the option orange
and save it to shared preferences with the key KEY_SPINNER_FRUIT_OPTION
what data type should the value be? Currently I'm saving it as Strings
orange
Would it be better to use Integer
instead?
String lastSelectedSpinnerOption = getSharedPref().getLastSavedValue("KEY_SPINNER_FRUIT_OPTION");
if(lastSelectedSpinnerOption.equals("orange")){
mSpinner.setSelection(2);
}
or
Integer lastSelectedSpinnerOption = getSharedPref().getLastSavedValue("KEY_SPINNER_FRUIT_OPTION");
if(lastSelectedSpinnerOption == 2){
mSpinner.setSelection(2);
}
Upvotes: 1
Views: 231
Reputation: 2108
If you will store Integer
your code won't be maintanable. If you change positions of elements(or add new element in saved position) in Spinner, your code won't work as expected.
What you can do is storing string value of chosen item into SharedPrefs
and then:
int position = adapter.getPosition(myValueFromSharedPrefs);
position = position > 0 ? position : 0; // if this element was removed, choose first item of the list
mSpinner.setSelection(position);
Upvotes: 2
Reputation: 325
Well there's no any best practice as on what type you should write in SharedPreferences
(as long as it is an accepted type for the API).
It actually totally depends on what you will do with this value.
If your goal is to save UI state and you're absolutely sure that the retained position will hold the same String
value, you could save the Integer
.
But I'd rather save the String
value as it is the user's intention to select an "orange" and when it is time to restore the UI state, I'd look for the position matching the "orange" value.
Upvotes: 2