Reputation: 3197
I tried to save and load the selected item in the spinner
using sharedPreferences
. Even though the code shows no errors, it's not working. Somebody help.
country=(Spinner)findViewById(R.id.spinner);
spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.countries_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
public void saveFile(){
SharedPreferences sharedPref = getSharedPreferences(FileName,Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPref.edit();
int userChoice = country.getSelectedItemPosition();
editor.putInt("userChoiceSpinner",userChoice);
}
public void readFile(){
SharedPreferences sharedPref = getSharedPreferences(FileName,Context.MODE_PRIVATE);
int spinnerValue = sharedPref.getInt("userChoiceSpinner",0);
country.setSelection(spinnerValue);
}
Upvotes: 0
Views: 57
Reputation: 1802
You set country and spinner both same id show may one spinner not set data
country=(Spinner)findViewById(R.id.spinner);
spinner = (Spinner) findViewById(R.id.spinner);
Upvotes: 0
Reputation: 69689
You forgot to use editor.apply();
to save value in SharedPreferences
SharedPreferences
object it is editing. This atomically performs the requested modifications, replacing whatever is currently in the SharedPreferences
. Try this
public void saveFile(){
SharedPreferences sharedPref = getSharedPreferences(FileName,Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPref.edit();
int userChoice = country.getSelectedItemPosition();
editor.putInt("userChoiceSpinner",userChoice);
editor.apply();
}
Upvotes: 1