androidactivity-lifecyclefragment-lifecycle

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 has listener like following,

public class SomeFragment extends Fragment {
    public interface SomeListener {
        public void onStartDoingSomething(Object whatItIsDoing, Date when);
        public void onDoneDoingTheThing(Object whatItDid, boolean result);
    }

    private SomeFragmentListener listener;
    private String[] args;

    public static SomeFragment getInstance(SomeListener _listener, String... _args) {
        SomeFragment sf = new SomeFragment();
        sf.listener = _listener
        sf.args = _args

        return sf;
    }

    // rest of the class

    // the example of where do I invoke the listener are
    // - onSetVisibilityHint
    // - When AsyncTask is done
    // - successfully download JSON
    // etc.
} 

How can I have the listener to bundle so that I can get it back later?


Solution

  • 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.

    public class TheFragment extends Fragment {
        private TheFragmentListener listener;
    
        @Override
        public void onAttach(Context context) {
            if (context instanceof TheFragmentContainer) {
                listener = ((TheFragmentContainer) context).onRequestListener();
            }
        }
    
        public void theMethod() {
            // do some task
            if (listener != null) {
                listener.onSomethingHappen();
            }
        }
    
        public interface TheFragmentContainer {
            public TheFragmentListener onRequestListener();
        }
    
        public interface TheFragmentListener {
            public void onSomethingHappen();
        }
    }