在MenuItem类型的可空接收器上只允许安全(?。)或非空断言(!!。)调用

时间:2018-05-13 10:25:14

标签: android kotlin

我正在尝试在android studio中为选项菜单项添加事件,但是当我使用item.itemId时收到此错误消息

  

在可空的上只允许安全(?。)或非空的断言(!!。)调用   MenuItem类型的接收器

这是我的代码

override fun onOptionsItemSelected(item: MenuItem?): Boolean {

if(item.itemId==R.id.home){
    var homeIntent= Intent(this,SignIn::class.java)
    startActivity(homeIntent)

}
else if(item.itemId==R.id.sign_in){
    var signInIntent= Intent(this,SignIn::class.java)
    startActivity(signInIntent)

}
else if(item.itemId==R.id.close){
    System.exit(0)

}


return super.onOptionsItemSelected(item)
}

2 个答案:

答案 0 :(得分:3)

问题是Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim nama, uname, password, email, jk As String Dim idusr As Integer nama = TextBox1.Text uname = TextBox2.Text password = TextBox3.Text email = TextBox5.Text jk = ComboBox1.SelectedValue Randomize() ' The program will generate a number from 0 to 50 idusr = Int(Rnd() * 50) + 1 If TextBox1.Text = "" Or TextBox2.Text = "" Or TextBox3.Text = "" Or TextBox4.Text = "" Or TextBox5.Text = "" Then MsgBox("Please Fill All The Box First !!!") ElseIf TextBox3.Text <> TextBox4.Text Or TextBox3.TextLength <= 8 Then MsgBox("Password do not match or missing !!!") Else Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Michael\Tugas Materi Kuliah\VB\TA\DBUtama.accdb" Dim conn = New OleDbConnection(dbsource) Dim str = "Insert into [User]([IDUSR],[Nama],[Uname],[Pass],[Jenis Kelamin],[Email]) Values ('" & idusr & "','" & nama & "','" & uname & "','" & password & "','" & jk & "','" & email & "') ;" Dim cmd As OleDbCommand = New OleDbCommand(str, conn) Try cmd.ExecuteNonQuery() cmd.Dispose() Catch ex As Exception MsgBox("Something broke, i know its you !!") End Try End If End Sub 定义为item。因此,在使用之前,您需要确保它不应该是nullable

null

或者您可以使用override fun onOptionsItemSelected(item: MenuItem?): Boolean { if(item?.itemId==R.id.home){ var homeIntent= Intent(this,SignIn::class.java) startActivity(homeIntent) } else if(item?.itemId==R.id.sign_in){ var signInIntent= Intent(this,SignIn::class.java) startActivity(signInIntent) } else if(item?.itemId==R.id.close){ System.exit(0) } return super.onOptionsItemSelected(item) }

let

答案 1 :(得分:0)

在这种情况下,避免这种情况的最简单方法是在第一行添加elvis运算符

item ?: return false

但在这种特殊情况下,您可以确定该项目在设计上不是空的,因此您可以安全地从方法声明中删除问号

override fun onOptionsItemSelected(item: MenuItem): Boolean {