I have a Kotlin extension function to add a fragment which is in another Kotlin file
fun Fragment.addFragment(tag: String?, id: Int, fragmentManager: FragmentManager) {
// will take care of adding the fragment.
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.add(id, this, tag)
fragmentTransaction.addToBackStack(tag)
fragmentTransaction.commit()
}
But whenever I am using that extension function to add a fragment then I am getting this crash
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.Fragment.setNextAnim(int)' on a null object reference
I am using that extension function like this:
MyFragment().addFragment("MyFragment", R.id.frame, fragmentMaganer)
After the above statement if I tried to debug my code then its executed successfully till
fragmentTransaction.commit()
but after that in the onStart() method of my activity I am facing that NullPointerException issue
But if I use the same code directly in Activity like this:
val myFragment = MyFragment()
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.add(R.id.frame, myFragment, tag)
fragmentTransaction.addToBackStack(tag)
fragmentTransaction.commit()
then Its working fine. Can someone please explain why its no working with Extension function?