Android: Save variables and settings on rotation

喜夏-厌秋 提交于 2019-12-02 10:32:59

You can save values into the instanceState Bundle when stopping an activity and restoring it when you start it. Like this:

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    // Read values from the "savedInstanceState"
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    // Save the values you need into "outState"
    super.onSaveInstanceState(outState);
}
Riot Goes Woof

Expanding on GSala's answer, this is sort of how I'd do it:

@Override
public void onSaveInstanceState(Bundle savedInstanceState){
    String someString = "this is a string";
    savedInstanceState.putString(CONSTANT_STRING, someString);
    //declare values before saving the state
    super.onSaveInstanceState(savedInstanceState);
}

Then in your onCreate you can get values like this:

@Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addContentView(R.layout.view);

        //Make sure to do this check otherwise someString will
        //cause an error when your activity first loads!
        if (savedInstanceState != null){
            //Do whatever you need with the string here, like assign it to variable.
            Log.d("XXX", savedInstanceState.getString(STRING_CONSTANT));
        }
}

This way, you don't have to Override onRestoreInstanceState as well. Also, this can be done with just about any variable or object, not just strings.

See this documentation for more information.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!