简体   繁体   English

错误“必需:找到字符串:字符串?” Kotlin和Android Studio

[英]Error “Required:String Found:String?” Kotlin and Android Studio

As the title suggests Im getting a red underline under "id" on the line "var myNote = Note(id, title, note, ServerValue.TIMESTAMP)" Error "Required:String Found:String?" 如标题所示,我在“ var myNote = Note(id,title,note,ServerValue.TIMESTAMP)”行的“ id”下获得红色下划线。错误“ Required:String Found:String?” Kotlin and Android Studio Kotlin和Android Studio

class MainActivity : AppCompatActivity() {
    var mRef:DatabaseReference? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val database = FirebaseDatabase.getInstance()
        mRef = database.getReference("Notes")

        add_new_note.setOnClickListener {
            showDialogAddNote()
        }
    }

    fun showDialogAddNote() {
        val alertBuilder = AlertDialog.Builder(this)

        val view = layoutInflater.inflate(R.layout.add_note, null)

        alertBuilder.setView(view)

        val alertDialog = alertBuilder.create()
        alertDialog.show()

        view.btnSaveNote.setOnClickListener {
            val title = view.etTitle.text.toString()
            val note = view.etNote.text.toString()

            if (title.isNotEmpty() && note.isNotEmpty()) {
                var id = mRef!!.push().key

                var myNote = Note(id, title, note, ServerValue.TIMESTAMP)
                mRef!!.child(id).setValue(myNote)
                alertDialog.dismiss()    
            } else {
                Toast.makeText(this, "Empty", Toast.LENGTH_LONG).show()
            }
        }
    }
}

Here is my Notes.kt class 这是我的Notes.kt类

package com.example.gearoidodonovan.books

import java.util.*

class Note (var id:String, var title:String, var note:String, var timestamp: MutableMap<String, String>) {
}

Kotlin forces you to be hyper-conscious about nullability. Kotlin迫使您对可空性保持高度的意识。

Your Note entity say its requires a non-nullable id:String , and apparently, mRef!!.push().key returns a String? 您的Note实体说它需要一个不可为空的id:String ,并且显然, mRef!!.push().key返回一个String? meaning it's a nullable String. 表示它是一个可为空的字符串。 You can fix this by double-banging it , ie mReff!!.push().key!! 您可以通过双击它来解决它,即mReff!!.push().key!!

Another tip is to ALT+ENTER these Kotlin related errors, it'll provide the double-bang for you. 另一个提示是要ALT+ENTER这些与Kotlin相关的错误,它将为您提供双重提示。

Your id property in Note is declared as non-null String , while the key you have is a potentially null String? 您在Note id属性被声明为非null String ,而您拥有的键可能是null String? . You need to bridge this gap. 您需要弥合这一差距。

  1. The simplest but most dangerous way is to use !! 最简单但最危险的方法就是使用!! , which will produce an exception if the key was null, ie ,如果key为null,即会产生异常,即

     var id = mRef!!.push().key!! 
  2. A better way is to handle the null case somehow, for example by performing a null check: 更好的方法是以某种方式处理空值情况,例如通过执行空值检查:

     var id = mRef!!.push().key if (id != null) { var myNote = Note(id, title, note, ServerValue.TIMESTAMP) mRef!!.child(id).setValue(myNote) alertDialog.dismiss() } else { // handle the case where key is null somehow } 
  3. You could also make the property in your own class nullable, and deal with the ID value in there potentially being null later: 您还可以将自己的类中的属性设置为可空,并在以后处理ID值(可能为null):

     class Note (var id: String?, var title: String, var note: String, var timestamp: MutableMap<String, String>) 

Note that all the mRef!! 注意所有的mRef!! calls are problematic as well. 通话也是有问题的。 For one, Hungarian notation (the m prefix) is generally discouraged in Kotlin, and the !! 例如,在Kotlin中通常不鼓励使用匈牙利符号( m前缀),而!! operator is dangerous as well. 操作员也是危险的。 You'd be better off handling the null case early for that reference, and then you could use it more conveniently, without having to litter your code with !! 您最好尽早处理该引用的空值,然后您可以更方便地使用它,而不必在代码中加!! .

I also encourage you to read up on null safety in general the official documentation or in this answer . 我也鼓励您通读正式文档此答案中的 null安全性。

您可以使用:

@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM