How to deal with device configuration changes such as change to the screen rotation?
Because whenever there is change in device configuration the activity gets destroyed and re-created,which meant that local variables used by the activity were lost.
There are two options: we can either tell Android to bypass restarting the activity, or we can save its current state so that the activity can re-create itself in the same state.
1) Bypass re-creating the activity
We can tell the android not to restart the activity if there's been a configuration change.Usually it's not the best option.This is because when Android re-creates the activity, it makes sure it uses the right resources for the new configuration. If you bypass this, you may have to write a bunch of extra code to deal with the new configuration yourself.
We can add some line of code in activity element in AndroidManifest.xml
Example:
<activity
android:configChanges="orientation|screenSize"
>
Here we are mentioning two things one is orientation and screenSize.Because when the device rotate the devices changes both the orientation and the screen size.
Now if the android experience these type of orientation changes,it makes a call to the 'onConfigurationChanged(Configuration)' method instead of re-creating the activity.
2)Save the current state
the better way of dealing with configuration changes is saving the current state of the activity,then reinstate it in the onCreate() method.
To save the current state we need to override a method onSaveInstanceState().
This method gets called just before activity gets destroyed so it is advisable to save the value of local variables.
This method takes only one parameter i.e a Bundle.
Bundle is used to store multiple values in a single object.
This Bundle object is passed to the onCreate() method. So the onCreate() method will be able to pick the values stored in the Bundle.
Code for saving the value inside onSaveInstanceState():
@Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
savedInstanceState.put*("key", value);
}
After storing the value we need to get these values in onCreate() method to save the state.
protected void onCreate(Bundle savedInstanceState)
{
savedInstanceState.get*("key");
}
In both method * represents the type of value we will be using like Int,String etc.

Awesome
ReplyDelete