Search code examples
androidandroid-layoutandroid-fragmentsfragmentandroid-fragmentactivity

getSupportFragmentManager().findFragmentById(R.id.fragment_container) returns null


I tried many solution nothing is working for me. I have build my fragment (MainFragment) to display in main activity. And in Main Activity I am using a FrameLayout ask a fragment_Container. Following code always returns null when for my MainFragment:

FragmentManager fm = getSupportFragmentManager();

fm.beginTransaction()
  .add(R.id.fragment_container, MainFragment.newInstance(),"mainFragment")
  .commit();

MainFragment mainFragment = (MainFragment) fm.findFragmentByTag("mainFragment");

Solution

  • The problem is because you try to get the MainFragment with the id by:

    MainFragment mainFragment = (MainFragment) fm.findFragmentById(R.id.fragment_container);
    

    which is wrong, because you can't be sure what is the Fragment within the container. And because the id is the container id not the Fragment id.

    You need to get the MainFragment by using the tag that you have already use before in:

    fm.beginTransaction()
      .add(R.id.fragment_container, MainFragment.newInstance(),"mainFragment")
      .commit();
    

    Here the tag is mainFragment. So call it by using findFragmentByTag:

    MainFragment mainFragment = (MainFragment) fm.findFragmentByTag("mainFragment");
    

    You can only use findFragmentById if you have declared the Fragment with id in the layout with something like:

    <fragment class="com.example.SampleFragment"
        android:id="@+id/sample_fragment"
        android:layout_width="match_parent" 
        android:layout_height="match_parent" />
    

    Then you can get the fragment by its id:

    MainFragment mainFragment = (MainFragment) fm.findFragmentById(R.id.sample_fragment);
    

    Furthermore, you can't get the MainFragment if you trying to get it after adding via FragmentManager like this:

    fm.beginTransaction()
      .add(R.id.fragment_container, MainFragment.newInstance(),"mainFragment")
      .commit();
    
    // This won't work!
    MainFragment mainFragment = (MainFragment) fm.findFragmentByTag("mainFragment");
    

    Because when you calling MainFragment.newInstance(), the process is asynchronous where the MainFragment haven't created yet. So you will pointing to null.