14

I'm getting this error while trying to launch a Fragment from a first Fragment :

java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.FragmentTransaction android.app.FragmentManager.beginTransaction()' on a null object reference

Here's the method where I'm getting the error :

    @Override
    public void onClick(View v) {
        Fragment fragment = new PropertyFragment();
        if (fragment != null) {
            FragmentManager fragmentManager = fragment.getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack so the user can navigate back
            fragmentTransaction.replace(R.id.rent_viewer, fragment);  
            fragmentTransaction.addToBackStack(null);

            // Commit the transaction
            fragmentTransaction.commit();  
        }
    }

Precisely, the following code instruction is causing the error :

fragmentManager.beginTransaction();

Here's how the class and the nested class look like :

public class RentFragment extends Fragment {    

    ...

    @SuppressWarnings("unused")
    private OnRentFragmentInteractionListener mListener;

    public RentFragment() {
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnRentFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnRentFragmentInteractionListener");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);         
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_rent, container, false);                

        myOnClickListener = new RentOnClickListener(getActivity());                     

        return rootView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {          
        super.onViewCreated(view, savedInstanceState);
    }   

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnRentFragmentInteractionListener {
        public void onRentFragmentInteraction(Uri uri);
    }

    private static class RentOnClickListener implements View.OnClickListener {

        private final Context context;

        private RentOnClickListener(Context context) {
            this.context = context;
        }

        @Override
        public void onClick(View v) {   
            Fragment fragment = new PropertyFragment();    
            if (fragment != null) {    
                FragmentManager fragmentManager =  fragment.getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

                // Replace whatever is in the fragment_container view with this fragment,
                // and add the transaction to the back stack so the user can navigate back
                fragmentTransaction.replace(R.id.rent_viewer, fragment);  
                fragmentTransaction.addToBackStack(null);

                // Commit the transaction
                fragmentTransaction.commit();  
            }   
        }        
    }       
}
hyunikel
  • 143
  • 1
  • 1
  • 6

5 Answers5

13

FragmentManager will be null until it is attached to the activity.So use below code , If it is a nested Fragment use this.getChildFragmentManager() for your fragment class else use getActivity().getFragmentManager() or getActivity().getSupportFragmentManager().

sharp
  • 1,191
  • 14
  • 39
Krish
  • 3,860
  • 1
  • 19
  • 32
  • The onClick method is in a nested static listener class. I can't use this which must refer to Fragment class. How can I access it please? – hyunikel Jan 02 '15 at 16:03
  • Thank you @Krish, all I had to do is to remove the word static from the nested listener class, and and a get instance method in the container class. So my instruction became : FragmentManager fragmentManager = getRentFragment().getActivity().getFragmentManager(); – hyunikel Jan 02 '15 at 19:45
1

Declare your FragmentTransaction and initialize it like this

FragmentTransaction fm;

@Override
public void onAttach(@NonNull Context context) {
    super.onAttach(context);
    fm = getFragmentManager();
}

Then on your code, you can call this

Fragment fragment = new PropertyFragment();
FragmentTransaction transaction = fm.beginTransaction();
transaction.add(R.id.rent_viewer, fragment).addToBackStack(null).commit();;
SilverC0de
  • 11
  • 1
  • 2
0

Use the Customize Method in Base Class and use it.

public void replaceFragment(Fragment newFragment, Bundle bundle, boolean isAddToBackStack) {

        String tag = newFragment.getClass().getSimpleName();
        if (bundle != null) {
            newFragment.setArguments(bundle);
        }

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

        if (getCurrentFragment() != null) {
            ft.hide(getCurrentFragment());
        }
        ft.add(R.id.frameContainer, newFragment, tag);
        newFragment.setRetainInstance(true);
        if (isAddToBackStack) {
            ft.addToBackStack(tag);
        }
        try {
            ft.commitAllowingStateLoss();
        } catch (Exception ex) {
            ex.printStackTrace();
//            ft.commitAllowingStateLoss();
        }
    }
Barry
  • 3,303
  • 7
  • 23
  • 42
Alok Singh
  • 640
  • 4
  • 14
0

You have to set context of activity as shown below on code HomeActivity.this.getSupportFragmentManager();

private Fragment fragment;
private FragmentManager fragmentManager;
fragmentManager=HomeActivity.this.getSupportFragmentManager();
 transaction = fragmentManager.beginTransaction();
 transaction.add(R.id.main_container,  new ProfileFragment()).commit();
Dharman
  • 30,962
  • 25
  • 85
  • 135
-2
     FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        fragmentTransaction.replace(R.id.rent_viewer, fragment);  
        fragmentTransaction.addToBackStack(null);

        // Commit the transaction
        fragmentTransaction.commit();  
Asthme
  • 5,163
  • 6
  • 47
  • 65