Search code examples
androidandroid-fragmentsandroid-fragmentactivityandroid-configchanges

Fragment being reset after configuration change


I'm currently creating an app using a bluetooth connection. The connection is handled inside an simple object (HandleConnection). When the connection is made, my app goes into "remote" mode, which means I'm replacing my main fragment with another one (RemoteFragment) which use the "HandleConnection" object.

Until the everything is going well, since at the end of my "onCreate" (inside my activity) I set the RemoteFragment's handleConnection attribute:

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_layout);


    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
    if (savedInstanceState == null) {
        retainedFragment = new RetainedFragment();
        getFragmentManager().beginTransaction().add(retainedFragment, RetainedFragment.class.toString()).commit();
        handleConnection = new HandleConnection(this, handler);
        retainedFragment.setHandleConnection(handleConnection);

    } else {

        remoteFragment = (RemoteFragment) getFragmentManager().findFragmentByTag(RemoteFragment.class.toString());
        retainedFragment = (RetainedFragment) getFragmentManager().findFragmentByTag(RetainedFragment.class.toString());

        if (remoteFragment == null)
            remoteFragment = new RemoteFragment();

        handleConnection = retainedFragment.getHandleConnection();
        remoteFragment.setHandleConnection(handleConnection);
    }

    fragmentTransaction.commit();

}

Everything works fine except when I turn into landscape mode. Then (after playing in debug mode), it seems my RemoteFragment is recreated after my setter is called, which obviously mean my handleConnection attribute is null. Why is it doing that ? I would understand if I didn't reuse the previous fragment (then I would have two different fragments on top of each other) but in this case it makes non sense. I made a workaround by calling a callback function inside the onCreateView to get the HandleConnection object, but why would the attribute be null when I called a setter right before ?

Thanks !


Solution

  • So apparently my problem was that I wasn't using the right instance of my RemoteFragment, which means my current reference (in my activity) had the correct non-null value for my object, but the fragment displayed wasn't this one (it was the old one which was recreated and thus had a null value for the handleConnection).