4

There's stuff I'd like to do in my Activities' onCreate() method only if they're constructed the first time, not when the device was rotated (on configuration changes). Currently I'm checking the savedInstanceState parameter passed into onCreate() for this. If it's null, then it's the first time the Activity starts, else there was only a rotation.

Is this a good and reliable way to tell this? Are there alternatives to this?

Zsombor Erdődy-Nagy
  • 16,864
  • 16
  • 76
  • 101

1 Answers1

3

I don't know of a better solution. Romain Guy describes the same approach (checking savedInstance state or other objects you pass for null).

In the new activity, in onCreate(), all you have to do to get your object back is to call getLastNonConfigurationInstance(). In Photostream, this method is invoked and if the returned value is not null, the grid is loaded with the list of photos from the previous activity:

private void loadPhotos() {
    final Object data = getLastNonConfigurationInstance();

    // The activity is starting for the first time, load the photos from Flickr
    if (data == null) {
        mTask = new GetPhotoListTask().execute(mCurrentPage);
    } else {
        // The activity was destroyed/created automatically, populate the grid
        // of photos with the images loaded by the previous activity
        final LoadedPhoto[] photos = (LoadedPhoto[]) data;
        for (LoadedPhoto photo : photos) {
            addPhoto(photo);
        }
    }
}

When I am lazy to do this, I just disable recreating the Activity on orientation change. As described at How do I disable orientation change on Android?

Community
  • 1
  • 1
Daniel Novak
  • 2,746
  • 3
  • 28
  • 37