在NavigationUI上执行命令时发生NullPointerException

时间:2019-06-15 16:02:12

标签: android navigation uinavigationcontroller

无法找到导致空异常的问题的原因。由指南进行项目,它没有这个问题。使用与guidr中相同的库版本。

错误消息

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)
}

}

3 个答案:

答案 0 :(得分:0)

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

这似乎是造成它的原因。很奇怪,因为在指导中不会造成任何麻烦。

答案 1 :(得分:0)

setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
navController = Navigation.findNavController(this, R.id.nav_host_fragment)

您在setSupportActionBar(toolbar)setContentView之间缺少navController = ...

答案 2 :(得分:-2)

只需注释以下行:

NavigationUI.setupActionBarWithNavController(this, navController)