Search code examples
androidandroid-fragmentsandroid-fragmentactivity

Fragment not attached to activity after commit


I'm working with Android Fragment and I got an issue when calling getString method. It throws an exception

10-12 07:43:18.309: E/AndroidRuntime(2425): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test/com.test.TestActivity}: java.lang.IllegalStateException: Fragment TestFragment{2c691b80 id=0x7f070015} not attached to Activity

My code is the following code in my Activity:

public void addFragment(IFragment fragment)
{
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();       
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        transaction.add(R.id.dual_layout_pane, fragment);
        transaction.commit();

        if (fragment.getActionBarTitle() != null) setTitle( fragment.getActionBarTitle() );
}

And in my Fragment class:

@Override
public String getActionBarTitle()
{
    return getString(R.string.login_title);
}

The error occurs on that line return getString(R.string.login_title);.

Is there a way to solve that kind of issue ?

Thanks for your precious help.


Solution

  • Is there a way to solve that kind of issue ?

    Delay your title change until onAttach() of the fragment. A FragmentTransaction is asynchronous; it will not be attached by the time commit() returns.

    There is a function however, commitNow() that will attach the fragment right away.