save value of spinner selected item using shared p

2019-05-06 23:07发布

问题:

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

My current code:

 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){}
    });

回答1:

I thought what you want is-At some point,you want to show your saved value(comes from shared preference) in the spinner as selected item.For this

set spinner adapter with all the default values that includes your saved value.Now you want to show your saved value as selected.Suppose you have 6 items in the 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 save spinner value at shared preference do this

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