-1

I wanted to ask that how can we store the value of spinner so that when the user visits the activity next time his last choice is saved.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62

1 Answers1

0

try this

//if use in activity then remove context
    Spinner spinner =(Spinner) findViewById(R.id.spinner);
            SharedPreferences sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
            final SharedPreferences.Editor editor = sharedpreferences.edit();
            int position = sharedpreferences.getInt("lastSelectedPosition",0);
            spinner.setSelection(position);

            spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    editor.putInt("lastSelectedPosition", position);
                    editor.commit();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
Bhupat Bheda
  • 1,968
  • 1
  • 8
  • 13
  • in the code, we used SharedPreference to save data.https://developer.android.com/training/basics/data-storage/shared-preferences.html – Bhupat Bheda May 05 '17 at 12:05
  • SharedPreference store the data while your application is installed.When your app is uninstalled or clear data then saved data automatically delete – Bhupat Bheda May 05 '17 at 12:07
  • so we are saved last selected spinner item in the preference and spinner.setSelection(position); it will move spinner item in last selected item – Bhupat Bheda May 05 '17 at 12:13
  • Glad it worked.Please accept my answer.You can also visit : https://stackoverflow.com/tour to get more information about SO and support me as much as you can. – Bhupat Bheda May 06 '17 at 04:37