I have a button that increase a variable by one and the result is printed in a TextView. When I rotate the device the variable value is maintained, but if I exit the activity and then re-enter, every value is reset. How can I fix this?
int n=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prova);
final TextView tv = (TextView)findViewById(R.id.tvProva);
Button b = (Button)findViewById(R.id.bProva);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
n++;
tv.setText(""+n);
}
});
if(savedInstanceState!=null){
n = savedInstanceState.getInt("n");
tv.setText(""+n);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("n", n);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.getInt("n");
}