My understanding is that when you change the device orientation, your app gets destroyed and created again. This means that onCreate() should run every time I rotate the device.
I’m trying to set an EditText every time the app is created, including whenever the screen is rotated. So, I start up the app, and the text field says “Bap”. I then change the contents of the field to “Boop”, then rotate the screen. I would expect the field to now say “Bap”, but it doesn’t, it remains whatever it was after I changed it, before the orientation change. Why is this?
My onCreate() looks like this:
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText editText = (EditText)findViewById(R.id.edit_message);
editText.setText("Bap", TextView.BufferType.EDITABLE);
}
It’s worth noting that if I move the setText() call into onResume(), everything works as I would expect it to, with the text field resetting every time I rotate the device.
NOTE: I realize a similar question has been asked, but the answer given doesn’t really explain why this behaviour is occuring.
It is happening because the Android framework is doing what it is supposed to. It is saving a bundle (SavedInstanceState) with all the information on the current state of your app, to be used when it re-creates your view after the orientation change.
Did you leave some code out of the onCreate you posted? Maybe something like:
If your onCreate code is wrapped in an if like that, that is why you are not seeing the results you expect.
It is standard practice to have an onCreate that looks like this:
This is done so you don’t needlessly re-create everything on an orientation change.
Hope this helps!
EDIT
Looking into it further, it looks like what is happening is this (gleaned from here):
device orientation change
It’s basically saying that the bundle is getting passed to
onRestoreInstanceState, which occurs afteronCreate, which would explain what is happening in your case.So, the solution would be to move the setting of the EditText value to your
onResumemethod (or overridingonRestoreInstanceState).