user1448108
user1448108

Reputation: 487

Values changing when app turns from portrait mode to landscape mode in android

I am working on android apps. My app should work both in portrait and landscape mode. I adjusted all the layouts by keeping all layout files in layout-lan folder. But now my issue is with functionality i.e when the app is changed to landscape mode the values of my parameters are changing and due to this I am getting crashes. i.e i kept a counter value but it is displaying wrong count value when turned to port-lan. Also the functionality is changing due to this. Please help me in this regard.

Upvotes: 0

Views: 1187

Answers (3)

Marko Niciforovic
Marko Niciforovic

Reputation: 3591

Each time you rotate the devide, onCreate method is being called again. You can save the values by overriding onSavedInstanceState and get them back in onRestoreInstanceState or in onCreate method. For example:

save the value:

 public void onSaveInstanceState(Bundle outState) {
        outState.putBoolean("booleanValue", true);
}

restore the value (you can call this in onCreate as well):

 protected void onRestoreInstanceState(Bundle savedInstanceState) {
        if (savedInstanceState != null && savedInstanceState.containsKey("booleanValue")) {
            boolean myBoolean = savedInstanceState.getBoolean("booleanValue");
        }
        super.onRestoreInstanceState(savedInstanceState);
    }

Upvotes: 1

Budius
Budius

Reputation: 39846

those values change because the activity gets destroyed and re-built during rotation,

please check the developers guide on how to save your activity state.

http://developer.android.com/training/basics/activity-lifecycle/recreating.html#SaveState

Upvotes: 0

Dark.Rider
Dark.Rider

Reputation: 391

Your activity restarts every time the orientation changes.

You have to store your values in onSaveInstanceState and restore them in onRestoreInstanceState. You will find the details here: http://developer.android.com/guide/topics/resources/runtime-changes.html

Upvotes: 0

Related Questions