I'm aware of activity state saving and restoring. But what I want to do is saving and restoring the state of a view. I have a custom view and two overrided methods in it:
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (state instanceof Bundle) {
Bundle bundle = (Bundle) state;
currentLeftX = bundle.getInt(CURRENT_LEFT_X_PARAM, 0);
currentTopY = bundle.getInt(CURRENT_TOP_Y_PARAM, 0);
}
super.onRestoreInstanceState(state);
}
@Override
protected Parcelable onSaveInstanceState() {
super.onSaveInstanceState();
Bundle bundle = new Bundle();
bundle.putInt(CURRENT_LEFT_X_PARAM, currentLeftX);
bundle.putInt(CURRENT_TOP_Y_PARAM, currentTopY);
return bundle;
}
I expected this to work seamless, but encountered and 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/mapViewId. Make sure other views do not use the same id. at android.view.View.onRestoreInstanceState(View.java:6161)
But this view is the only one in my activity. So, I'm asking:
What is the right way to save the state of the view?
The savedInstanceState is a reference to a Bundle object that is passed into the onCreate method of every Android Activity. Activities have the ability, under special circumstances, to restore themselves to a previous state using the data stored in this bundle.
The saveState() method allows your component to return a Bundle containing any state that should be saved from that component. SavedStateRegistry calls this method during the saving state phase of the UI controller's lifecycle.
Restore your activity state When your activity is recreated after it was previously destroyed, you can recover your saved state from the Bundle that the system passes to your activity. Both the onCreate() and onRestoreInstanceState() callback methods receive the same Bundle that contains the instance state information.
The onSaveInstanceState() method allows you to add key/value pairs to the outState of the app. Then the onRestoreInstanceState() method will allow you to retrieve the value and set it back to the variable from which it was originally collected.
You drop the result of super.OnSaveInstanceState()
and return your own.
Then later at OnRestoreInstanceState(Parcelable)
you return the one which you created.
The solution for that is here:
How to prevent custom views from losing state across screen orientation changes #2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With