This feels like a noob question, but in Android, when the orientation changes the Activity is destroyed and recreated, and onCreate() is called anew. Internal state can be saved via a savedInstanceState bundle. So far so good.
But in my app I have an activity which is normally invoked from another activity via startActivityForResult(), which passes in a bunch of parameters. In onCreate() the target activity does a getIntent() to retrieve the passed-in data. The problem is that when that activity is on the screen and I flip the orientation it crashes. It's crashing in the onCreate() code, where it calls getIntent(). I presume it's crashing because there's nothing to "get" since in that case it's being invoked from the system instead of from the other activity.
What's the correct way to handle this? How do I tell when my onCreate() is being called due to an orientation change so I don't try to call getIntent()? Or am I just thinking about this wrong? Thank you in advance.
If you want to manually handle orientation changes in your app you must declare the "orientation" , "screenSize" , and "screenLayout" values in the android:configChanges attributes. You can declare multiple configuration values in the attribute by separating them with a pipe | character.
When you rotate your device and the screen changes orientation, Android usually destroys your application's existing Activities and Fragments and recreates them . Android does this so that your application can reload resources based on the new configuration.
Some device configurations change while the application is running, such as when the device changes its orientation. Such a change restarts the activity by calling all its methods again.
You can save the details that you get by the getIntent()
method in the savedInstanceState. That means, in your onSaveInstanceState(Bundle)
store the info that you use in the onCreate()
using the getIntent()
. When your activity
is newly created, in the onCreate(Bundle savedInstanceState)
method, the bundle savedInstanceState
is null. So you can make a check condition in your onCreate(Bundle savedInstanceState)
, if the Bundle savedInstanceState
is null that means you need to get the data using getIntent()
else if its not null that means there was some oritentation change and you need to get the data using the savedInstanceState
bundle.
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