简体   繁体   中英

onSaveInstanceState not getting variable after onCreate

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.

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?

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.

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);
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM