0

I tried to open my second fragment from my 1st fragment but that giving me error. I tried as This answer and I google it everywhere done the same but not worked for me. I also tired with this android fragment transaction doc but didn't understand. Please can some one explain and solve this error in simpler way. Here is my code :

            FragmentManager fragmentManager=getActivity().getFragmentManager();
            FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.profile_f, new UProfileFragment()); //My second Fragment | & | home_layout is frame layout
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();

and Here is my android studio screen error Screenshot :

Image Screenshot of exact error

Edit : Thank you for your answers this problem was due to androidx library and old android library's code mix up. i was using the old app compact library instead of androidx library. i changed the fragment and function to androidx and it did work. Note for new Android developer: please use one compact library's code (either androidx or android old)

iamnabink
  • 454
  • 9
  • 27

3 Answers3

3

As already suggested, use getSupportFragmentManager() AND make sure that your UProfileFragment inherits from androidx.fragment.app.Fragment in case you use AndroidX or android.support.v4.app.Fragment in case you don't.

Your Activity should inherit from AppCompatActivity

Droidman
  • 11,485
  • 17
  • 93
  • 141
2

try this one code

FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.home_layout, new ChatFragment(), "UProfileFragment"); //My second Fragment
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
0

You forget to extend your UProfileFragment class with android.app.Fragment. Also, you should either use android.support.v4.app.Fragment or android.app.Fragment or androidx.fragment.app.Fragment if you are using AndroidX.

Vatish Sharma
  • 1,536
  • 3
  • 16
  • 35