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);
}
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();
}
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.