Saving and retrieving spinner value with sharedpreferences

810 Views Asked by At

I have a spinner. I want to save its value in saveFile() and retrieve the same on calling readFile() using sharedpreferences. I haven't got the right way to do it yet.

    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();
     }
    public void readFile(){
            SharedPreferences sharedPref = getSharedPreferences(FileName,Context.MODE_PRIVATE);
    }
3

There are 3 best solutions below

6
DNA.h On BEST ANSWER

Try this

     public void saveFile(){
            SharedPreferences sharedPref = getSharedPreferences(FileName,Context.MODE_PRIVATE);
            SharedPreferences.Editor editor=sharedPref.edit();
            editor.putInt("spinnerValue",spinner.getSelectedItemPosition());
            editor.apply();
     }

     public void readFile(){
            SharedPreferences sharedPref = getSharedPreferences(FileName,Context.MODE_PRIVATE);
            int index = sharedPref.getInt("spinnerValue",0);
            spinner.setSelection(index);
     }
5
navylover On

You should add

  editor.apply();

after set preference value.

0
Abu Yousuf On

To save data in Shared Preference you have to write data to Shared Preference. For writing data use :

SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score_key), newHighScore);
editor.commit();

And to read again use this:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.integer.saved_high_score_default_key);
int highScore = sharedPref.getInt(getString(R.string.saved_high_score_key), defaultValue);

Check official doc for more.