Using shared prefernences to save String but having difficulty saving my spinner.
public class MainActivity extends Activity {
Spinner spnExample;
Button btnSave;
ArrayAdapter<CharSequence> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSave = (Button) findViewById(R.id.btnSave);
SharedPreferences prefs;
loadData();
spnExample = (Spinner) findViewById(R.id.spnExample);
adapter = ArrayAdapter.createFromResource(this, R.array.country_arrays, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnExample.setAdapter(adapter);
spnExample.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position) + " selected", Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Here is where I am saving my preferences behind a button (in onCreate)
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = getPreferences(0).edit();
EditText etName = (EditText) findViewById(R.id.etName);
editor.putString("editTextCallIdtext", etName.getText().toString());
int selectedPosition = spnExample.getSelectedItemPosition();
editor.putInt("spinnerSelection", selectedPosition);
editor.commit();
}
});
}
This the method I am using to load the preferences (outside onCreate)
private void loadData() {
SharedPreferences prefs = getPreferences(0);
EditText etName = (EditText) findViewById(R.id.etName);
String etNametextrestored = prefs.getString("editTextCallIdtext", null);
spnExample.setSelection(prefs.getInt("spinnerSelection",0));
etName.setText(etNametextrestored, EditText.BufferType.EDITABLE);
}