NullpointerException when findFragmentById

2019-09-19 10:07发布

问题:

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);

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

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

            //Pass data to fragment
            /*NullpointerException, contentFragment is null!*/
            contentFragment.setArguments(data);

            setContentView(R.layout.activity_main);
        }
...   
}

I try to find the fragment in onCreate() of Activity, and then pass some data to it. But when I findFragmentById(...), I got NullpointerException, Why?

回答1:

You can't perform a findFragmentById before adding the fragment to your activity. When you make a setContentView the Actvitiy inflates the layout and adds its views to the current window. In the case of having a Fragment in this layout, it is added with the given Id or Tag provided in the xml to the FragmentManager. Only in this moment you can find it there. So what you have to do is move the findFragmentById below the setContentView.



回答2:

You should move

 setContentView(R.layout.activity_main);

before

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

You got NPE because findFragmentById(R.id.fragment_content) failed to find fragment with id fragment_content.