Search code examples
androidandroid-fragmentsnullpointerexceptionandroid-viewpagerandroid-tablayout

Null Pointer Exception When Setting ViewPager for TabLayout


I have a fragment that will contain two other fragments that can be accessed through a TabLayout

I have the following Kotlin code:

class TutorialFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {

        val tutorialview = inflater.inflate(R.layout.fragment_tutorial, container, false )

        tutorialview.tutorialViewPager.adapter = TutorialFragmentPagerAdapter(context!!, fragmentManager!!)

        //Null Pointer Exception on this line 
        tabBar.setupWithViewPager(tutorialview.tutorialViewPager)


        return tutorialview
    }

    companion object {
        fun newInstance() = TutorialFragment()
    }
}

My code crashes with the exception:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.TabLayout.setupWithViewPager(android.support.v4.view.ViewPager)' on a null object reference
        at com.vedantroy.animefacekeyboard.home.tutorial.TutorialFragment.onCreateView(TutorialFragment.kt:23) 

Update 1 -

As per the suggestion of Tuby,

I changed my code to:

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {

    Log.d("KEYBOARD-APP","Inside tutorial fragment onCreate()...")
    val tutorialView = inflater.inflate(R.layout.fragment_tutorial, container, false )
    tutorialView.tutorialViewPager.adapter = TutorialFragmentPagerAdapter(fragmentManager!!)
    tutorialView.tabBar.setupWithViewPager(tutorialView.tutorialViewPager)

    return tutorialView
}

However, although the fragment itself is now showing, the tabs are not.


Solution

  • Error clearly says the TabLayout is null

    Try changing

    tabBar.setupWithViewPager(tutorialview.tutorialViewPager)

    to

    tutorialview.tabBar.setupWithViewPager(tutorialview.tutorialViewPager)