Saving Activity state on Android when change orientation

In Android application when we change the orientation of device then our activity is recreated and some time we face the NullPointerException. To handle NullPointerException or other exceptions we can save current state and retrive the values or tell in AndroidManifest.xml that don’t destroy this activity.

Solution 1:Tell in AndroidManifest that don’t destroy this activity on orientation change. Just add following android:configChanges in your activity tag.

Solution 2:

If you don’t want to keep continue with android’s default behaviour that is Android re-instatiate our activity and load every thing from start then you can save current activity state (values) and then get that values onCreate or onRestoreInstanceState

We will override onSaveInstanceState to save the values. It calls onSaveInstanceState automatically before destroying the activity.

Get these values in onCreate or in onRestoreInstanceState overrided functions

Get these values in onCreate function. I will prefer onCreate function insted of onRestoreInstanceState