Solution to screen rotation in android

If you are new to android development then you must be facing this issue. The problem on screen rotation is that when you rotate the screen that time the activity instance is destroyed and new instance is generated of the same activity. So to avoid this problem we have to understand the flow of Android Activity life cycle.

Android_doc-basic_lifecycle

From the above flow chart before calling OnDestroy method the onRestoreInstanceState is called. This the state where we have to restore the instance of previous activity before getting destroy.

 

Solution to the problem with example.

Take a look to the following example. In this example we have one textView and one EditTextBox. On Screen rotation the value on the both textview and editTextbox is restored to initial value.

Have a look to our XML layout.

Android Rotation problem

Now moving to java code. Here we are using onSaveInstanceState method to save the instance of activity so that the textView and EditTextBox does not revert to initial value. Have a look at snippet of onSaveInstanceState.

Now to store back the instance we have to use onRestoreInstanceState method. So that the value are reverted back to its normal values which user had entred. Here is the snippet of onRestoreInstanceState.

Finally here is the full code to resolve the rotation problem.

If you are still facing this problem then feel free to comment down below and will be happy to help you.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.