ManiTeja
ManiTeja

Reputation: 847

save value of spinner selected item

How can I save the current selected spinner value, such that when I reopen the application the saved value is automatically selected by default?

Upvotes: 0

Views: 7878

Answers (5)

mango
mango

Reputation: 5636

you can also refer to the spinner value by position. that way you need only to deal with ints straight-fowardly:

    SharedPreferences settings = getSharedPreferences("MYPREFS", 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putInt("VALUE", spinner.getSelectedItemPosition());
    editor.commit();

and to load:

spinner.setSelection(settings.getInt("VALUE", 0));

Upvotes: 0

Deepanker Chaudhary
Deepanker Chaudhary

Reputation: 1704

For set value one another way:---

         for(int i=0;i<adapter.getCount();i++){
            if(adapter.getItem(i).equals(your save preference value){
                spinner_timer.setSelection(i);      
                }
         }

Upvotes: 0

Dipak Keshariya
Dipak Keshariya

Reputation: 22291

Please Write below code on onItemSelectedListener() of spinner and store selected value into shared preferences.

String mSpnValue=mSpinner1.getSelectedItem().toString();
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("Value", mSpnValue);

Use below code for set item as selected in spinner.

SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String myString = myPrefs.getString("Value","nothing"); // the value you want the

ArrayAdapter<String> myAdap = (ArrayAdapter<String>) mSpinner1.getAdapter();
int spinnerPosition = myAdap.getPosition(myString);

// set the default according to value
mSpinner1.setSelection(spinnerPosition);

Upvotes: 3

Aracem
Aracem

Reputation: 7207

You can use several methods

For example you can use a DataBase and save on it.

Other methods, and the best IMO, is used SharedPreferences http://developer.android.com/intl/es/reference/android/content/SharedPreferences.html

http://developer.android.com/intl/es/reference/android/app/backup/SharedPreferencesBackupHelper.html

Upvotes: 0

Iulia Barbu
Iulia Barbu

Reputation: 1530

You can save spinner position in preferences and when entering back use spinner.setSelection(position_from_preferences);

Upvotes: 1

Related Questions