1

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.

Foobar
  • 7,458
  • 16
  • 81
  • 161
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) –  Jul 01 '18 at 21:43

2 Answers2

2

Error clearly says the TabLayout is null

Try changing

tabBar.setupWithViewPager(tutorialview.tutorialViewPager)

to

tutorialview.tabBar.setupWithViewPager(tutorialview.tutorialViewPager)

Tuby
  • 3,158
  • 2
  • 17
  • 36
  • Hmm.. I did that and the exception went away. However, the tabs themselves are still not showing. – Foobar Jul 01 '18 at 22:24
  • You might be missing titles for tabs or there is something wrong inside xml layout – Tuby Jul 02 '18 at 08:19
0

For some reasons, android studio is not auto importing the library at the top, I suggest you do that manually.

add this as a top level declaration in TutorialFragment

import com.google.android.material.tabs.TabLayout
Mubarak Tahir
  • 207
  • 3
  • 4