Skip to content Skip to sidebar Skip to footer

How To Get And Set Selected Item From Spinner Using Sharedpreferences

I want to store selected item from spinner and once that fragment is again launch , previous selected Item should be selected , I tried but not able to get it. I need to store sele

Solution 1:

I had used editor.putInt("VALUE", spinner.getSelectedItemPosition());

Solution 2:

You need to set the selected value each time you initialize the spinner in the Framgent's onCreateView where this code already resides:

spinner_level = (Spinner)rootView.findViewById(R.id.spinner_activity_level);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(rootView.getContext(), R.array.activity_level, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinner_level.setAdapter(adapter);
spinner_level.setGravity(Gravity.CENTER);
spinner_level.getSelectedItemPosition();
int indexOfPreviousSelection = sharedPreferences.getInt("selectionIndex", 0);
spinner_level.setSelection(indexOfPreviousSelection);

You need to get indexOfPreviousSelection from SharedPreferences, I presume you know how to do that. And also you need to set the new value each time it changes:

@OverridepublicvoidonItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
    ((TextView) parentView.getChildAt(0)).setTextColor(Color.BLACK);
    selected = parentView.getItemAtPosition(position).toString();
    SharedPreferences.Editoreditor= sharedPreferences.edit();
    editor.putInt("selectionIndex", position);
    editor.apply();
}

SharedPreferences sharedPreferences should be a field in your Framgent which you'll initialize in onAttach or where you deem appropriate:

@OverrideprotectedvoidonAttach(Context context) {
    super.onAttach(context);
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

Post a Comment for "How To Get And Set Selected Item From Spinner Using Sharedpreferences"