Skip to content Skip to sidebar Skip to footer

Save Interface (listener) In Onsaveinstancestate

SaveInstanceState For data like Integer, Long, String and else are fine, I just put it in the bundle and get it back once the onCreateView gets called again. But my fragment also h

Solution 1:

I recently just found the proper way to do this and I want to share for future reader of this topic.

The proper way to save listener of the fragment is not to save it, but instead, request from activity when fragment got attached to activity.

publicclassTheFragmentextendsFragment {
    private TheFragmentListener listener;

    @Override
    publicvoidonAttach(Context context) {
        if (context instanceof TheFragmentContainer) {
            listener = ((TheFragmentContainer) context).onRequestListener();
        }
    }

    publicvoidtheMethod() {
        // do some taskif (listener != null) {
            listener.onSomethingHappen();
        }
    }

    publicinterfaceTheFragmentContainer {
        public TheFragmentListener onRequestListener();
    }

    publicinterfaceTheFragmentListener {
        publicvoidonSomethingHappen();
    }
}
  • when the fragment attach to an activity, we check if activity implement TheFragmentContainer or not
  • if the activity does, request listener from activity.

Solution 2:

Any Classes without a suitable .put method in Bundle need to implement Serializable (as do any objects used within) or implement Parcelable (the latter is preferred). You can then use the putParcelable or putSerializable methods on Bundle.

Post a Comment for "Save Interface (listener) In Onsaveinstancestate"