2

I found out that Android destroys and recreates activities during screen orientation changes. I have an Activity that automatically looks up the device's nominal location and displays it back to the user. This location is stored in a record-keeping object that is used throughout the course of the application. Here's my code:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.location);

    currentLocation = (TextView) findViewById(R.id.textCurrentLocation);
    if (savedInstanceState == null)
        new LocationDetectionTask(this).execute((Void[]) null);
    else
        currentLocation.setText(record.getLocation());

    Log.d(TAG, "onCreate");
}

(As you might be able to tell, record represents that data record object).

Is this method of handling screen orientation changes sufficient? By the way, I am not overriding onSaveInstanceState(Bundle).

Also, a side question: since LocationDetectionTask is an AsyncTask, how do I go about handling screen orientation changes for that?

Edit: I forgot to clarify this. After the LocationDetectionTask finds the location, it puts it in the record.

kibibyte
  • 3,007
  • 5
  • 30
  • 40
  • 1
    As a side comment. http://stackoverflow.com/questions/4584015/handle-screen-orientation-changes-when-there-are-asynctasks-running – Malachi Jul 28 '11 at 22:08

1 Answers1

2

You should try to use onSaveInstanceState(Bundle) to save your information as this will get called before the activity destroys itself on orientation change. I would try to use onRestoreInstanceState(Bundle) when getting the information back, but it should work on the onCreate() method too. (An example here Saving Android Activity state using Save Instance State)

Keep in mind that the Bundle should be used to save primitive types. If you want to pass a more complex object, you can try to pass a Parcelable object. (More info here http://prasanta-paul.blogspot.com/2010/06/android-parcelable-example.html)

Community
  • 1
  • 1
Ken
  • 1,498
  • 2
  • 12
  • 19