Marcin S.
Marcin S.

Reputation: 11191

onSaveInstanceState() and onRestoreInstanceState(Parcelable state) are not called?

I have a custom view that extends LinearLayout. I have implemented onSaveInstanceState() and onRestoreInstanceState() to save the current view state. However no any action is taken. When I place a log inside of those two methods also nothing appears in Log Cat. I assume that those two methods are not even called. Can anybody explain where is the problem? Thanks.

@Override
public Parcelable onSaveInstanceState() {
    Bundle bundle = new Bundle();
    bundle.putParcelable("instanceState", super.onSaveInstanceState());
    bundle.putInt("currentPage", currentPage);
    return bundle;
}

@Override
public void onRestoreInstanceState(Parcelable state) {

    if (state instanceof Bundle) {
      Bundle bundle = (Bundle) state;
      currentPage = bundle.getInt("currentPage");
      Log.d("State", currentPage + "");
      super.onRestoreInstanceState(bundle.getParcelable("instanceState"));
      return;
    }
       super.onRestoreInstanceState(state);
  }

Upvotes: 11

Views: 6165

Answers (2)

Adam Johns
Adam Johns

Reputation: 36373

As Steven Byle's comment mentioned, a custom View must have an id assigned to it for onSaveInstanceState to be called. I accomplished this by setting an id in my custom View constructor:

public class BoxDrawingView extends View {
    private int BOX_DRAWING_ID = 555;
    …

    public BoxDrawingView(Context context, AttributeSet attrs) {
        …
        this.setId(BOX_DRAWING_ID);
    }
    …

}

Upvotes: 4

Marcin S.
Marcin S.

Reputation: 11191

After digging in android os I have finally figured it out. As I suspected: there is nothing wrong with those two methods. They are just not called. On the Web you can read that 'onRestoreInsatnceState is called when activity is re-created' Ok, it make sens but it's not completely true. Yes, onRestoreInstanceState() is called when activity is recreated but only iff:

it was killed by the OS. "Such situation happen when:

  • orientation of the device changes (your activity is destroyed and recreated)
  • there is another activity in front of yours and at some point the OS kills your activity in order to free memory (for example). Next time when you start your activity onRestoreInstanceState() will be called."

So if you are in your activity and you hit Back button on the device, your activity is finish()ed and next time you start your app it is started again (it sounds like re-created, isn't?) but this time without saved state because you intentionally exited it when you hit Back button.

Upvotes: 4

Related Questions