Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save and Retrieve Selected Spinner Position

How would you save and retrieve a spinners selection, so when you come back the same item on the spinner is selected? Maybe with shared preferences?

like image 883
user1832006 Avatar asked Nov 17 '12 14:11

user1832006


1 Answers

to Save data on the sharedPreferences( put this code on the onItemSelected() method and save the selected value's position of your spinner) :

int userChoice = spinner.getSelectedItemPosition();
SharedPreferences sharedPref = getSharedPreferences("FileName",0);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putInt("userChoiceSpinner",usersChoice);
prefEditor.commit();

To get data from sharedPreferences :

SharedPreferences sharedPref = getSharedPreferences("FileName",MODE_PRIVATE);
int spinnerValue = sharedPref.getInt("userChoiceSpinner",-1);
if(spinnerValue != -1) {
  // set the selected value of the spinner 
  spinner.setSelection(spinnerValue);
}

refer this : set selection in spinner and this : get the position of the selected item in a spinner

See Also :

  • Android Tutorial : Using SharedPreferences

  • Android Tutorial : Switch Between Activities and Pass Data Between Them

like image 63
Houcine Avatar answered Sep 19 '22 16:09

Houcine