Android – How to maintain spinner state in android

androidandroid-spinner

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 1.apple 2.orange 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:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(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

  spinner.getSelectedItemPosition(); 

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

  prefEdit.putInt(); 

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

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

OR TRY LIKE THIS

to Save:

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

to Load:

yourSpinner.setSelection(prefs.getInt("spinnerSelection",0));

if you are array used it should changed like this

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

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.