NullPointerException on executing command on NavigationUI

Viewed 3340

Cant find what causes the problem with null exception. Making the project by the guide and it doesnt have this problem. using the same libraries versions like in guidr.

Error message

Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.navigation.ui.NavigationUI
import androidx.navigation.ui.setupWithNavController
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private lateinit var navController: NavController
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        navController = Navigation.findNavController(this, R.id.nav_host_fragment)
        bottom_nav.setupWithNavController(navController)


        NavigationUI.setupActionBarWithNavController(this, navController)

    }

    override fun onSupportNavigateUp(): Boolean {
        return NavigationUI.navigateUp( navController, null)
    }
}
2 Answers
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
navController = Navigation.findNavController(this, R.id.nav_host_fragment)

you are missing setSupportActionBar(toolbar) between setContentView and navController = ...

res/values/styles under the app theme:

<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>

this seems to cause it. strange, because in guide it doesn't cause any trouble.

Related