VorteXavier VorteXavier - 22 days ago 6
Java Question

onSaveInstanceState is not getting called after screen rotation

I know there are lots of quetions regarden onSaveInstanceState but I wasn't able to find an answer to my problem.

I have an activity that extends AppCompatActivity; this activity uses 3 fragments and it has a variable 'int currentStep' to track which fragment is being displayed. In the onSavedInstanceState method I store the currentStep variable in the bundle, and then in onCreate method I restore it.

public class MainActivity extends AppCompatActivity {
private final String CURRENT_STEP_TAG = "current_step";
private int currentStep;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pedido);

if(savedInstanceState == null) {
loadFirstFragment();
} else {
currentStep = savedInstanceState.getInt(CURRENT_STEP_TAG);
if(currentStep == 2){
//Do some stuff...
}
}
}

@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
Log.d("deubg", "--------onsaveinstancestate--------");
outState.putInt(CURRENT_STEP_TAG, currentStep);
super.onSaveInstanceState(outState, outPersistentState);
}

...

}


The thing is that onSavedInstanceState won't get called when screen orentation changes, and according to google documentation, it should. The message "--------onsaveinstancestate--------" doesn't show in the console.
However the Bundle savedInstanceState in the method onCreate is non null after screen rotation, but it doesn't have the int 'currentStep'.

I've tried many things: changed AppCompatActivity for ActionBarActivity, moved the call for super.onSavedInstanceState to different locations, tried to store other variables; but no matter what I do the method doesn't execute.

Also I DO NOT have android:configChanges in my manifest.

My application is being compiled against sdk version 22, buildToolsVersion 22.0.1

Answer

Unless your app is running on API21+ version of Android, your

public void onSaveInstanceState (Bundle outState, PersistableBundle outPersistentState);

will NOT be called as it simply does not exist on earlier versions of the platform than 21. To support pre API 21 devices you must, instead of the above, override the following method:

public void onSaveInstanceState (Bundle outState);

This will work on API 21+ as well, so you do not need to override both methods, of course (unless you know you need to deal with PersistableBundle the new one offers).

See docs.

Comments