错误"Required:String Found:String?" Kotlin和Android Studio [英] Error "Required:String Found:String?" Kotlin and Android Studio
问题描述
正如标题所示,我在"var myNote = Note(id(标题,标题,说明,ServerValue.TIMESTAMP)")行的"id"下获得红色下划线 错误必需:找到的字符串:字符串?" Kotlin和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?" Kotlin and 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()
}
}
}
}
这是我的Notes.kt类
Here is my Notes.kt class
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.
您的Note
实体说它需要一个不可为null的id:String
,显然,mRef!!.push().key
返回一个String?
表示它是可为null的字符串.您可以通过双击将其修复,例如mReff!!.push().key!!
Your Note
entity say its requires a non-nullable id:String
, and apparently, mRef!!.push().key
returns a String?
meaning it's a nullable String. You can fix this by double-banging it , i.e. mReff!!.push().key!!
另一个提示是ALT+ENTER
这些与Kotlin相关的错误,它将为您提供双重效果.
Another tip is to ALT+ENTER
these Kotlin related errors, it'll provide the double-bang for you.
这篇关于错误"Required:String Found:String?" Kotlin和Android Studio的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!