Headless fragment persists but looses all data

104 Views Asked by At

I have a headless fragment with some data. It all works ok-ish until the app gets killed by the OS to recover resources. Once that happens my fragments reports as alive, however all internal objects of the instance are null. I'm not sure what I'm doing wrong but something is definitely wrong. Here's my code:

Activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
<...stuff...>

    if (savedInstanceState == null) {
        initStateFragment();
    } else {
        mFragment = (HeadlessFragment) getSupportFragmentManager()
                .findFragmentByTag(HeadlessFragment.STATE_HEADLESS_FRAGMENT_TAG);
        // here mFrament is NOT null but internal objects are nulls
    }

Fragment:

public MyState state;
public SomeStuff someStuff;
public SomeStuff.Mode mode;
public SomeMoreOtherStuff moreStuff;
public Uri uri;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setRetainInstance(true);
}

public interface OnStateChangeListener {
    public void onStateChangeAttach(MyState state, Uri uri);
}

private WeakReference<OnStateChangeListener> mOnStateChangeListener;

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mOnStateChangeListener = new WeakReference<>((OnStateChangeListener) activity);
        mOnStateChangeListener.get().onStateChangeAttach(state, uri);
    } catch (ClassCastException e) {
        throw new <...>
    }
}

So to summarise, after the activity was paused and then killed by the OS to recover resources, on going back to the app .findFragmentByTag will find a fragment, however it's internal parameters will all be null

0

There are 0 best solutions below