[FIXED] Calling setSupportActionBar in a fragment

Issue

How can I call setSupportActionBar in a fragment in kotlin language .
I have a mainActivity with a navigation drawer. When I click on the first item of the navigation drawer it should opens a notesFragment . I want to set a toolBar for the notesFragment. When I tried to use AppCompatActivity().setSupportActionBar(toolbar_top) the app crashes when I click on the first item of the navigation drawer, with the error

java.lang.NullPointerException: Attempt to invoke virtual method ‘android.view.Window$Callback android.view.Window.getCallback()’ on a null object reference

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

        AppCompatActivity().setSupportActionBar(toolbar_top)
        AppCompatActivity().getSupportActionBar()!!.setDisplayShowTitleEnabled(false)
        fragments()

        AppCompatActivity().getSupportActionBar()!!.setDisplayHomeAsUpEnabled(true)

        return inflater!!.inflate(R.layout.main_fragment,null)
    }

    fun fragments() {
        var tabLayout=tab
        var viewPager=viewPager
        var adapter=viewPagerAdapterMainActivity(AppCompatActivity().supportFragmentManager)
        adapter.addFragment(firstFragment(),"first")
        adapter.addFragment(secondFragment(),"second")
        adapter.addFragment(thirdFragment(),"third")

        viewPager.adapter=adapter
        tabLayout.setupWithViewPager(viewPager)
    }

}

Solution

As you’re using Kotlin you can try to smart cast the activity to AppCompatActivity and then you can access the support action bar:

(activity as AppCompatActivity).supportActionBar

Note that this will only work if your host activity extends AppCompatActivity.

Answered By – Levi Moreira

Answer Checked By – David Goodson (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published