I have an app with two layouts (portrait and landscape). There are 4 int values I want to save so they don't get erased on rotation. For that, I call on save instance and then I recover the state on the onCreate method like this:
private int operando1;
private int operando2;
private int operador;
private int contadorIntentos;
private String operadorTxt;
private static final String CONTADOR_INTENTOS = "contadorIntentos";
private static final String OPERANDO1 = "operando1";
private static final String OPERANDO2 = "operando2";
private static final String OPERADOR = "contadorIntentos";
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(CONTADOR_INTENTOS, contadorIntentos);
outState.putInt(OPERANDO1, operando1);
outState.putInt(OPERANDO2, operando2);
outState.putInt(OPERADOR, operador);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_actividad_principal);
//other random code
Random generador = new java.util.Random();
if (savedInstanceState != null){
contadorIntentos = savedInstanceState.getInt(CONTADOR_INTENTOS);
operando1 = savedInstanceState.getInt(OPERANDO1);
operando2 = savedInstanceState.getInt(OPERANDO2);
operador = savedInstanceState.getInt(OPERADOR);
}else {
contadorIntentos = 0;
operando1 = generador.nextInt(1000);
operando2 = generador.nextInt(1000);
operador = generador.nextInt(4);
}
Well, it turns out that it only saves the state once. after the first rotation (when it saves correctly) if I modify things and rotate again it recovers the state of the first rotation. It's like onsaveinstancestate only works once. Why?
0 comments:
Post a Comment