Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getIntent() when orientation changes - how to handle this?

Tags:

android

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.

like image 320
user316117 Avatar asked Jun 24 '13 17:06

user316117


People also ask

How can we cope with screen orientation changes?

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.

How does the Activity respond when the user rotates the screen?

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.

What happened to the app's Activity when the user rotate the device?

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.


1 Answers

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.

like image 101
Antrromet Avatar answered Sep 28 '22 00:09

Antrromet