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:
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.
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.
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