Android – Save / Load state Fragment

public class SomeFragment extends Fragment {
 
    public final static String OBJECT_ATTR = "object";
    Data data;
 
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
 
        /**
         * restore
         */
        if(savedInstanceState != null) {
            data = savedInstanceState.getParcelable(OBJECT_ATTR);
        }
 
        /**
         * using data
         */
        ...
    }
 
    /**
     * called when configuration change, but not on getting fragment from back-stack
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        /**
         * save
         */
        super.onSaveInstanceState(outState);
        outState.putParcelable(OBJECT_ATTR, data);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *