• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

615
Views
Error "¿Requerido:Cadena encontrada:Cadena?" Kotlin y Android Studio

Como sugiere el título, aparece un subrayado rojo debajo de "id" en la línea "var myNote = Note(id, title, note, ServerValue.TIMESTAMP)" Error "¿Requerido:Cadena encontrada:Cadena?" Kotlin y 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() } } } }

Aquí está mi clase 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>) { }
over 3 years ago · Santiago Trujillo
3 answers
Answer question

0

Kotlin te obliga a ser hiperconsciente sobre la nulabilidad.

Su entidad Note dice que requiere una id:String no anulable, y aparentemente, mRef!!.push().key devuelve una String? lo que significa que es una cadena anulable. Puede arreglar esto golpeándolo dos veces, es decir, mReff!!.push().key!!

Otro consejo es ALT+ENTER en estos errores relacionados con Kotlin, te proporcionará el doble golpe.

over 3 years ago · Santiago Trujillo Report

0

Su propiedad de id en Note se declara como String no nula, mientras que la clave que tiene es una String? . Necesitas cerrar esta brecha.

  1. ¡La forma más simple pero más peligrosa es usar !! , que producirá una excepción si la key era nula, es decir

     var id = mRef!!.push().key!!
  2. Una mejor manera es manejar el caso nulo de alguna manera, por ejemplo, realizando una verificación nula:

     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. También puede hacer que la propiedad en su propia clase sea anulable y tratar con el valor de ID que podría ser nulo más adelante:

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

Tenga en cuenta que todos los mRef!! Las llamadas también son problemáticas. Por un lado, la notación húngara (el prefijo m ) generalmente se desaconseja en Kotlin, y el !! el operador también es peligroso. ¡Será mejor que maneje el caso nulo temprano para esa referencia, y luego podría usarlo de manera más conveniente, sin tener que ensuciar su código con !! .

También lo animo a leer sobre seguridad nula en general la documentación oficial o en esta respuesta .

over 3 years ago · Santiago Trujillo Report

0

Puedes usar:

@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")

over 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error