Reputation: 147
Hi can someone explain me please what I am doing wrong because I cannot get a variable from savedInstanceState, int "score" every time I change my screen orientation it resets the variable.
int score;
EditText et;
String etString;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText);
if (savedInstanceState != null) {
score = savedInstanceState.getInt("score");
et.setText(savedInstanceState.getString("etText"));
Log.d("TEST2", "score " + score);
} else {
score = 0;
}
}
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
etString = et.getText().toString();
outState.putString("etText", etString);
outState.putInt("score", score);
Log.d("TEST", "score " + score);
}
public void performAction(View v) {
switch (v.getId()) {
case R.id.button:
score += 1;
break;
case R.id.button2:
Toast.makeText(getApplicationContext(), "Score: " + score, Toast.LENGTH_LONG).show();
break;
}
}
Please help if you know the solution.
Upvotes: 1
Views: 102
Reputation: 3372
public class OrientationChangeActivity extends Activity {
private EditText edtUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtUser = (EditText) findViewById(R.id.edtUsername);
if (savedInstanceState != null /*&& savedInstanceState.getString("edt") != null*/) {
edtUser.setText(savedInstanceState.getString("edt"));
Log.e("Demo","==================================="+savedInstanceState.getString("edt"));
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("edt", edtUser.getText().toString());
super.onSaveInstanceState(outState);
}
}
Upvotes: 0
Reputation: 3137
You should implement onRestoreInstanceState
instead of getting value in onCreate
. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null.
Upvotes: 0
Reputation: 39836
you're using a method that is from Lollipop, change to the version that is available since Android 1.0
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
see the different method signature?
Upvotes: 1