Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onCreate(...) is called twice after the device is rotated

Tags:

android

I have a question about rotating the Android device. My code logs a static and non-static attribute in onCreate(...).

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {
    static int sn;
    int n;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        sn++;
        n++;

        Log.i("onCreate", String.format("sn=%d n=%d", sn, n));
    }
}

The screen orientation is portrait. When I first ran the code, I got:

onCreate(): sn=1 n=1

After I rotated the screen to landscape, I got:

onCreate(): sn=2 n=1

After I rotated the screen again to portrait, I got:

onCreate(): sn=3 n=1
onCreate(): sn=4 n=1

My questions are:

  1. How can I prevent onCreate(...) to be called twice when the device is rotated back to portrait?
  2. How can I save the value of non-static variable when the device is rotated?
like image 276
wannik Avatar asked Nov 07 '11 03:11

wannik


2 Answers

This is a known issue in the emulator (see the discussion here). It's not a bug, but it is an issue for many people going back years. As I understand it, the basic problem is that your activity is restarted twice when it goes into portrait mode because the emulator is handling two configuration changes separately: the orientation change itself and the deactivation of the keyboard. It doesn't happen in the other direction because there isn't a configuration change event corresponding to activation of the keyboard. (I find this strange, but evidently this is the desired behavior for some reason.)

In any event, the solution seems to be this to add this to your activity manifest declaration:

android:configChanges="keyboardHidden|orientation"

If you actually require those changes to load new resources, you can manually handle it in onConfigurationChanged.

like image 98
Ted Hopp Avatar answered Sep 28 '22 00:09

Ted Hopp


Whenever the screen orientation is changed, that Activity is destroyed and a new activity starts by onCreate() method. so every time you rotate the screen that activity will be destroyed and a new activity starts by onCreate() method. You can save Non Static member by overriding onSaveInstanceState(Bundle b) method. Android calls this method whenever the screen is rotated, and that given bundle b would be passed to oncreate(Bundle b) from which you can extract your non static member.

like image 38
Aakash Avatar answered Sep 28 '22 01:09

Aakash