Android Fragment getArguments() returns null

@tonny

I've download the FragmentBasics.zip. I only change the argument name. Here is the code and result pic.

MainActivity

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.news_articles);

    // Check whether the activity is using the layout version with
    // the fragment_container FrameLayout. If so, we must add the first fragment
    if (findViewById(R.id.fragment_container) != null) {

        // However, if we're being restored from a previous state,
        // then we don't need to do anything and should return or else
        // we could end up with overlapping fragments.
        if (savedInstanceState != null) {
            return;
        }

        // Create an instance of ExampleFragment
        HeadlinesFragment fragment = new HeadlinesFragment();

        // In case this activity was started with special instructions from an Intent,
        // pass the Intent's extras to the fragment as arguments
//            firstFragment.setArguments(getIntent().getExtras());
        //test
        Bundle args= new Bundle();
        args.putString("category", "clothes");
        args.putString("item", "shirts");
        fragment.setArguments(args);

        // Add the fragment to the 'fragment_container' FrameLayout
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, fragment).commit();
    }
}

HeadlinesFragment

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // We need to use a different list item layout for devices older than Honeycomb
    int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
            android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;

    Bundle args = getArguments();
    if (args == null) {
        Toast.makeText(getActivity(), "arguments is null " , Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(getActivity(), "text " + args , Toast.LENGTH_LONG).show();
    }    

    // Create an array adapter for the list view, using the Ipsum headlines array
    setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.Headlines));
}

here is the result

enter image description here


I had the same problem, but solved it :)

My problem was that I had the <fragment android:name=""> element in the Activity's XML layout. Therefore the onCreate() of the Fragment was called before the calls in Java code, thus not setting the arguments.

I removed the <fragment> element from my XML layout and it worked!