Im new to android. I have written a couple of programs and tried them out on my phone. When I switch orientations its like my phone restarts the program. All my variables get reset. In fact the only thing that does not reset is the text that is in the edit text views. What causes this? How can I stop it? I have tried looking it on google and on stack overflow but all I am seeing is how to the view orientation from changing all together. I even tried, in one program, to set my variables with the get text method but this does not work.
When I switch orientations its like my phone restarts the program.
Well to be accurate, the currently visible Activity
is completely destroyed and recreated. Other components of your 'application' may or may not be impacted.
What causes this? How can I stop it?
It's by design and as for stopping it, you may or may not want to do that.
As has been mentioned, it is possible to specify that you want to handle 'configuration' changes (such as orientation) yourself or even force only one (e.g., landscape or portrait).
In many cases, however, an app developer may choose to change a layout based on whether a device is in one orientation or another. Some layouts may work fine in portrait but not in landscape (or vice versa) and the aim of the designed approach (to destroy / recreate the current visible Activity
) is meant to accommodate that.
If a dev chooses not to handle the configuration changes themself or force a specific orientation, the correct way to handle things is to make sure all data entered in 'volatile' UI elements (such as EditTexts) are correctly saved and recreated after orientation change.
To do this, understanding of the Activity
life-cycle is essential as is making use of the various Activity
methods that are called throughout the life-cycle to save / restore data.
Essential reading...
Runtime Changes
Activity Lifecycle
Application Fundamentals
make sure you implement onSaveInstanceState
and be prepared to restore your activity from a Bundle
in onCreate
and you'll be all set. these will be called during rotation, so you'll have a new activity afterwards, but if you've saved your state and can restore it, nothing to worry about.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With