Skip to content Skip to sidebar Skip to footer

Nullpointerexception When Findfragmentbyid

I have an Activity which hosts a Fragment. The Activity layout file: Copy

before

FragmentcontentFragment= getSupportFragmentManager().findFragmentById(R.id.fragment_content);

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

Solution 2:

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.

Post a Comment for "Nullpointerexception When Findfragmentbyid"