【发布时间】:2019-01-22 15:32:12
【问题描述】:
正如标题所示,我在“var myNote = Note(id, title, note, ServerValue.TIMESTAMP)”行的“id”下得到了一个红色下划线 错误“必需:找到的字符串:字符串?” 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()
}
}
}
}
这是我的 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>) {
}
【问题讨论】:
-
您的问题在概念上等同于:stackoverflow.com/questions/36465626/…
-
lateinit var mRef:DatabaseReference有助于避免! mRef 周围。mRef!!.push().key可以为空。是否可能由您的数据库决定。最安全的方法是添加对 null 的检查,例如 if 语句或使用 Elvis 运算符?:在左侧为 null 时传递表达式