Android – How to maintain spinner state in android


I'm doing an Android app which can get data from a web service & load it into spinner. I need to maintain the selected data state of the spinner while I go to some screen & come back. For example, if I'm getting data from the web service as 3.grapes & loading it into the spinner, then I select orange. When I go to some other screen & come back, the selected spinner data should be orange. But it again loads data from the server into the spinner. Can anybody help me to resolve this?

My code:

public void onCreate(Bundle savedInstanceState) {


    if (Constants.SPINNER != null ) {
        spinner.setSelection( Constants.SPINNER);
    } else {
        //WebCall here for getting data


    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent,
            View view, int arg2, long arg3) {
                Constants.SPINNER = spinner.getSelectedItemPosition();

In Constant class:

public static Integer SPINNER="";

Best Solution

You can use


that will return to you an int that you can save with


then when you want to re-load everything that has been saved you would just call

  spinner.setSelection(prefs.getInt("key", default));


to Save:

  int selectedPosition = yourSpinner.getSelectedItemPosition()
  editor.putInt("spinnerSelection", selectedPosition);

to Load:


if you are array used it should changed like this

 String selectedString = yourArray[yourSpinner.getSelectedItemPosition()];
   editor.putString("spinnerSelection", selectedString);

checking array[i] against the value stored in prefs.if you use an ArrayList instead this part could be done without the loop by calling

 ArrayList.indexOf(prefs.getString("spinnerSelection", "");

when you commit show all above array item gone. show no one into array.