No adapter attached to viewpager2

I have been trying to implement a viewpager2 in kotlin but i cannot figure out why am i getting an error saying no adapter attached to recycle view here is my MainActivity.kt:

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        binding = ActivityMainBinding.inflate(layoutInflater)
        binding.viewpager2.adapter = Viewpager2Adapter(this)
        TabLayoutMediator(binding.tabLayout , binding.viewpager2){
                tab, position ->
            tab.text = "OBJECT ${(position + 1)}"
        }.attach()
    }

}

Below is viewpager2Adapter.kt ::

class Viewpager2Adapter(fa : FragmentActivity): FragmentStateAdapter(fa)  {
    override fun getItemCount(): Int = 3

    override fun createFragment(position: Int): Fragment= Fragment2()

}

This is my fragment2.kt::

class Fragment2 : Fragment() {

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

        return inflater.inflate(R.layout.fragment_2, container, false)
    }
}

Can someone please help me by figuring out what is it that I am doing wrong. Thank you in advance 🙂

Answer

I think you did not use view binding properly in your MainActivity. In setContentView you should have binding.root instead of R.layout.activity_main

Here is the code for onCreate function in MainActivity:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view)

    viewpager2Adapter = Viewpager2Adapter(this)
    viewPager2 = binding.viewpager2
    tabLayout = binding.tabLayout
    viewPager2.adapter = viewpager2Adapter


    TabLayoutMediator(tabLayout, viewPager2){
            tab, position ->
        tab.text = "OBJECT ${(position + 1)}"
    }.attach()
}