Android Fragments NullPointerException error

1.2k views Asked by At

I'm trying to use the following code to open a Fragment that is inside another Fragment but is gives me a Null Pointer Exception with no cause.

Fragment newFragment = new SecondFragment(); 
// consider using Java coding conventions (upper char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.menuitem_detail_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit(); 

This piece of code is inside a basic onItemClickListener inside the onCreateView method inside of a Fragment (android.support.v4.app.Fragment)

Any ideas on what I might be doing wrong?

3

There are 3 answers

0
Sound Conception On

When you use nested fragments you need to getChildFragmentManager() for the inner fragments.

Also make sure you're importing from the support library for both the FragmentManager and ChildFragmentManager.

0
aterribili On

Look for my transaction.replace :

transaction.replace(R.id.provas_view, new ListaProvasFragment(), ListaProvasFragment.class.getCanonicalName());

0
tritop On

On getFragmentManager you should use getActivity().getSupportFragmentManager() or getChildFragmentManager() instead of getFragmentManager. If the NPE is thrown at transaction.replace(), you should make sure you are replacing a propper layout, eg with

RelativeLayout rl = (RelativeLayout) getActivity().findViewById(R.id.menuitem_detail_container);
transaction.replace(rl.getId(), newFragment);

Above is only an example because I don't know your Code, but you may get the Idea. In this example I asume the container layout you are using has the same name in the Activities XML.

Just make sure you don't try to replace something returning null. If you are using the container from your onCreate, try to Log it to find out if it is null.

If this isn't helping you, please post your Logcat output.