Reputation: 8467
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.
Upvotes: 1
Views: 1430
Reputation: 207
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
Upvotes: 0
Reputation: 3253
Error clearly says the TabLayout
is null
Try changing
tabBar.setupWithViewPager(tutorialview.tutorialViewPager)
to
tutorialview.tabBar.setupWithViewPager(tutorialview.tutorialViewPager)
Upvotes: 2