Bibin Johny
Bibin Johny

Reputation: 3197

Saving and loading spinner value using sharedPreferences

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

Answers (2)

mehul chauhan
mehul chauhan

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

AskNilesh
AskNilesh

Reputation: 69689

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

Upvotes: 1

Related Questions