1

I have a custom ViewGroup extending FrameLayout. On orientation change I need to persist one int value. I'm overriding the onSaveInstanceState() and onRestoreInstanceState(Parcelable state) to keep the old value. My code is given below

                @Override
                    protected Parcelable onSaveInstanceState() {
                        final Bundle bundle = new Bundle();
                        bundle.putInt(POSITION, position);
                        return bundle;
                    }

                    @Override
                    protected void onRestoreInstanceState(Parcelable state) {
                        if (state instanceof Bundle) {
                            Bundle bundle = (Bundle) state;
                            mPosition = bundle.getInt(POSITION);
                        }
                        super.onRestoreInstanceState(state);
                    }

But I'm getting a crash.

java.lang.IllegalStateException: Derived class did not call super.onSaveInstanceState()

But if I call super.onSaveInstanceState() on onSaveInstanceState how can I return my bundle value?

What is the issue here?

Thanks in advance!!

  • 1
    "But if I call super.onSaveInstanceState() on onSaveInstanceState how can I return my bundle value?" Why not? just make super.onSaveInstanceState() your first line. It'll work fine – mehulmpt Feb 27 '17 at 06:43
  • yes you can return your bundle value after callling super.onSaveInstanceState() – Rahul Kumar Feb 27 '17 at 06:44
  • But there is one issue. If I call ` super.onSaveInstanceState();` it will work , but `onRestoreInstanceState` again it will crash. The moment I call ` super.onRestoreInstanceState(state);` I will get the error `Caused by: java.lang.IllegalArgumentException: Wrong state class, expecting View State but received class android.os.Bundle instead. This usually happens when two views of different type have the same id in the same hierarchy. This view's id is id/frm. Make sure other views do not use the same id.` –  Feb 27 '17 at 06:53
  • @MehulMohan understood the issue? –  Feb 27 '17 at 06:59

1 Answers1

1

call super method in onSaveInstanceState()

 @Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);  // call super method
    // your code
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    // your code
}
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
  • Pls check my above comment –  Feb 27 '17 at 06:54
  • have a look at [this](http://stackoverflow.com/questions/19004722/overriding-onsaveinstancestate) create ur own `SavedState` with `Parcelable` data – rafsanahmad007 Feb 27 '17 at 07:00
  • Is this the only way? Then what is the intention of `onSaveInstanceState` and `onRestoreInstanceState` unless we can't pass our data directly? –  Feb 27 '17 at 07:25