5

I've an Activity and a Parcelable class that I want to save on orientation changes. Here is the code in the Activity:

Keeper keeper = ...;
@Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putParcelable("keeper", keeper);
  }

@Override
  protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    if (savedInstanceState != null) {
      keeper = savedInstanceState.getParcelable("keeper");
    }
  }

Here is the code of my Keeper class:

public class Keeper implements Parcelable {
  ...

    private int index; 
  @Override
  public int describeContents() {
    return 0;
  }

  @Override
  public void writeToParcel(Parcel dest, int flags) {
    Log.e("QQQQQQQ", "writeToParcel");
    dest.writeInt(index);
  }

  private Keeper(Parcel in) {
    Log.e("QQQQQQQ", "readfromParcel - Keeper");
    index = in.readInt();
  }

  public static final Parcelable.Creator<Keeper> CREATOR
      = new Parcelable.Creator<Keeper>() {
    public Keeper createFromParcel(Parcel in) {
      return new Keeper(in);
    }

    public Keeper[] newArray(int size) {
      return new Keeper[size];
    }
}

I don't see the Logs that are written in writeToParcel and in the Parcel constructor.. I've tried to close the app and simulate low memory so that Android kills the activity and i see the Logs!!! Does anyone know why?

MisaMisa
  • 273
  • 3
  • 7
  • 4
    `writeToParcel()` will only be called when the `Parcelable` is put into a `Parcel`. In this case, it would only be called when the saved instance state `Bundle` is put into a `Parcel`. There may be optimizations that avoid that overhead on a simple configuration change. – CommonsWare Feb 25 '15 at 18:53
  • @CommonsWare, would writing Keeper's data (rather than Keeper object) to the Bundle fix this? If so, I can write Parcelable only to Bundle and not Parcel.. would it work? – MisaMisa Feb 26 '15 at 07:16
  • "would... fix this?" -- there is nothing wrong and nothing to fix. Just because `writeToParcel()` is not being called does not mean that you are losing data. – CommonsWare Feb 26 '15 at 12:05
  • @CommonsWare i am having the same scenario. But in my case the very complex parcelable leaks memory this way. Is there a way to force the object to be parcelled? I mean that its really written like decribed and read like described (and therefore really 'recreated') – Martin Mlostek Sep 13 '15 at 08:08
  • 1
    @martynmlostekk: "Is there a way to force the object to be parcelled?" -- not really. If it is that complex, IMHO probably it should not be `Parcelable` in the first place. Use a retained fragment to deal with configuration changes. – CommonsWare Sep 13 '15 at 10:02

0 Answers0