Saving and loading spinner value using sharedPreferences

57 Views Asked by At

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);
}
2

There are 2 best solutions below

6
AskNilesh On

You forgot to use editor.apply(); to save value in SharedPreferences

editor.apply();

  • Commit your preferences changes back from this Editor to the 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();
    }
0
mehul chauhan On

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);