Home > Back-end >  How can I store two keys using push in realtime database?
How can I store two keys using push in realtime database?

Time:01-03

And sorry If I am too active these days but I have to deploy a project in a week and I am stuck. I have a problem with a double push to store data in Realtime Database with Kotlin. Please look at the picture. I need to store two key values, but I need to use two pushes to generate new children. I know how to save one of the keys but not both. I use a hashmap to create the date and after saving it, but one of the keys is not stored properly, just a random value. Any suggestions?

EDIT:

So my real problem is that comentarioID = referenciaBD.push().key!!.toString() is storing something which is not the key I need. Please look the picture I don't know how to express better in english

enter image description here

You can see my function to store the data here:

  private fun guardarComentario (uidPostRecibido:String) {
        val comentarioMap = HashMap<String, Any>()
        referenciaBD = FirebaseDatabase.getInstance().reference.child("Comentarios").child(uidPostRecibido)
        comentarioID = referenciaBD.push().key!!.toString()
        print(comentarioID)
        comentarioMap["comentarioID"]= comentarioID
        comentarioMap["publicacionID"]= uidPostRecibido
        comentarioMap["contenido"] = binding.etComentario.text.toString()
        comentarioMap["creadoPor"] = FirebaseAuth.getInstance().currentUser!!.uid
        comentarioMap["fecha"] = LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))
        referenciaBD.push().setValue(comentarioMap).addOnCompleteListener() { task ->
            if (task.isSuccessful) {
                Toast.makeText(context,"COMENTARIO GUARDADO EN LA BASE DE DATOS CON EXITO",Toast.LENGTH_SHORT).show()
                anadirNotifcacion(uidPostRecibido)
                binding.etComentario.setText("")
            } else {
                Toast.makeText(context, "ERROR GUARDANDO EN LA BD", Toast.LENGTH_SHORT).show()
            }
        }
    }

CodePudding user response:

If you need to save both pushed keys into a single field, then you can create a concatenation that looks like this:

db-root
 |
 --- Comentarios
       |
       --- -NKoX...qEQe
             |
             --- -NKr6..._dyP
                   |
                   --- comentarioID: "-NKr6..._dyO::-NKr6..._dyP"
//                                                           
  • Related