user842225
user842225

Reputation: 5999

'Fragment already active' when setArguments() to fragment

I have an Activity which hosts a Fragment.

The Activity layout file:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment class="com.my.ContentFragment"
        android:id="@+id/fragment_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</FrameLayout>

Java code of Activity:

import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;

public class ContentActivity extends ActionBarActivity {

     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);

            //data from  previous Activity
            Bundle data = getIntent().getExtras();

            Fragment contentFragment = getSupportFragmentManager()
                                                    .findFragmentById(R.id.fragment_content);

            // Pass data to fragment
            /*java.lang.IllegalStateException: Fragment already active*/
            contentFragment.setArguments(data);
        }
...   
}

I try to find the fragment in onCreate() of Activity, and then pass some data to it. But when I contentFragment.setArguments(data);, I get java.lang.IllegalStateException: Fragment already active.

Then I also checked contentFragment.getArguments() which is null. So, why I can not set arguments to my fragment?

If it is not possible to pass bundle to fragment this way, how can I pass the bundle to fragment?

Upvotes: 3

Views: 9294

Answers (2)

Anish Mittal
Anish Mittal

Reputation: 1182

Just use FrameLayout in your xml file instead of fragment tag. Then just create new Fragment object from onCreate() of your activity [above] and call fragment.setArguments(Bundle);.

And inside onCreate() of Fragment class, call getArguments(), which will return passed Bundle.

It is best approach ever to pass bundle to Fragment.

Upvotes: 0

sockeqwe
sockeqwe

Reputation: 15929

Arguments are typically read in Fragment.onCreate() .. If you inflate the Fragment from xml layout, then the fragment is already added through the FragmentManager to the activity and can not take arguments anymore.

If a fragment needs arguments it is better for you to add it to the FragmentManager programatically and not using the xml way. I encourage you to have a look to this doc where it is explained the correct fragment lifecycle and how to attach this fragment to the activity correctly.

Btw. you may find FragmentArgs useful.

Upvotes: 2

Related Questions