So this is my first app on android and it's working great. However, when I tilt the screen to its horizontal view then my integers get reset to zero. If I start horizontally then switch it to vertical, it resets the integers to zero too. How can I get it to not reset and just switch?
-
1Your app is restarted each time you tilt your device – Phantômaxx Jun 07 '14 at 16:30
3 Answers
Override onSaveInstanceState(Bundle outState)
method. Put your data in outState
bundle, and then, in onCreate(Bundle savedInstanceState)
, extract it from savedInstanceState
.
If your data is something more complex than a trivial integer, and does not implement Parcelable
interface, use Fragment
.

- 9,873
- 7
- 71
- 89
Your app will re-run an activity each time you tilt the device. You have to save the data in a shared preferences file before you rotate, because a rotate will kill the activity so that it can run again with the new orientation.
See this link on how to store the data: http://developer.android.com/reference/android/app/Activity.html#SavingPersistentState

- 3,312
- 2
- 23
- 35
-
Using `SharedPreferences` to store data between orientation changes is overkill. Moreover, it involves disk I/O, so orientation change will be slower. – Andrii Chernenko Jun 07 '14 at 16:37
-
@deville, thanks for the suggestion, what would you suggest instead? – ElectronicGeek Jun 07 '14 at 16:39
-
Instead, I would suggest overriding `onSaveInstanceState(Bundle outState)` method. Put your data in `outState` bundle, and then, in `onCreate(Bundle savedInstanceState)`, extract it from `savedInstanceState`. – Andrii Chernenko Jun 07 '14 at 16:46
If you don't want to save your data one quick 'fix' for this is to go into your AndroidManifest.xml file and do the following:
- Select the activity (I'm assuming it's your MainActivity)
- Find the field labeled 'screen orientation'
- Change it to 'portrait' (to keep the screen from changing when the phone is tilted horizontally)
You can also do this in the xml of your AndroidManifest file which would look something like this:
<activity
...
android:name="yourApp.MainActivity"
android:screenOrientation="portrait"
...
</activity>
Edit - Keeping in mind that
"this is my first app on android"
Locking the orientation is a perfectly reasonable way to stop this behavior if you're just testing things out but it is by no means a viable solution in any 'real' project.

- 3,769
- 2
- 30
- 33
-
1
-
Locking orientation isn't a 'fix' for what the OP is asking. Locking orientation is a design decision - it may be appropriate for certain app designs but shouldn't be used simply to prevent a configuration change in order to prevent re-creation of an `Activity`. – Squonk Jun 07 '14 at 17:17
-
1**"Locking the orientation is a perfectly reasonable way to stop this behavior if you're just testing things out "** - No it is not. A perfectly reasonable way to stop it happening when testing is simply not to rotate the device. – Squonk Jun 07 '14 at 17:42
-