A
It is correct what you do, you keep the element index inside the Spinner, but the value you're saving as whole and you're getting it like String which isn't right, by the way, you don't need to use commit(), with apply() That's enough:public void guardarPreference(Context context, int index) {
SharedPreferences sharpref = getPreferences(getApplicationContext().MODE_PRIVATE);
SharedPreferences.Editor editor = sharpref.edit();
editor.putInt("Dato", index);
System.out.println("Indice:"+index);
editor.apply();
//editor.commit();
}
If you keep the value whole, get it this way in your Activity SharedSpinner, you can define the 0 as default value.I recommend keeping the position in the Spinner when you select it (inside onItemSelected()). @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shared_spinner);
Spinner spSpinner = findViewById(R.id.idspinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.Lista, android.R.layout.simple_spinner_item);
spSpinner.setAdapter(adapter);
//Obtiene indice guardado en preferencias.
SharedPreferences sharpref = getPreferences(getApplicationContext().MODE_PRIVATE);
index = sharpref.getInt("Dato", 0);
//Mueve a esa posición el Spinner
spSpinner.setSelection(index);
spSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
CapturaSpinner = (String) parent.getItemAtPosition(position);
index = position;
System.out.println("Indice:"+index);
//Guarda indice de elemento seleccionado.
guardarPreference(getApplicationContext(), position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}