Save the value of the selected item using shared preferences

How to save the current selected value of the counter, so that when you re-open the application, the selected value is automatically saved?

My current code is:

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.loginpage); final Spinner spinner = (Spinner) findViewById(R.id.spinner1); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.spinner_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( getBaseContext()); SharedPreferences.Editor prefEditor = prefs.edit(); prefEditor.putString("savedValue",spinner.getSelectedItem().toString()); String savedValue=spinner.getSelectedItem().toString(); for(int i=0;i<6;i++) if(savedValue.equals(spinner.getItemAtPosition(i).toString())) { spinner.setSelection(i); break; } } @Override public void onNothingSelected(AdapterView<?> parent){} }); 
+4
source share
1 answer

I thought what you want - at some point you want to show the saved value (comes from general preference) in the spinner as the selected item. For this

install the spinner adapter with all the defaults that include your saved value. Now you want to show the saved value as the selected one. Suppose you have 6 elements in an adapter

 String savedValue=PreferenceManager .getDefaultSharedPreferences(context) .getString("savedValue",""); for(int i=0;i<6;i++) if(savedValue.equals(spinner.getItemAtPosition(i).toString())){ spinner.setSelection(i); break; } 

To keep the counter value under common preferences do this

  SharedPreferences prefs; prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor prefEditor = prefs.edit(); prefEditor.putString("savedValue",spinner.getSelectedItem().toString()); prefEditor.commit(); 
+5
source

All Articles