Monrac
Monrac

Reputation: 49

How can I store two keys using push in realtime database?

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()
            }
        }
    }

Upvotes: 1

Views: 53

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 139019

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"
//                                                👆

This solution is for holding both values within the same field of type String. Now, to get the values of both IDs, you have to read what exists on the left-hand side of the :: divider and then what's on the right-hand side.

Alternatively, you can save the value in an array-type field:

db-root
 |
 --- Comentarios
       |
       --- -NKoX...qEQe
             |
             --- -NKr6..._dyP
                   |
                   --- comentarioID: ["-NKr6..._dyO", "-NKr6..._dyP"]

Another solution would store both values in a map:

db-root
 |
 --- Comentarios
       |
       --- -NKoX...qEQe
             |
             --- -NKr6..._dyP
                   |
                   --- comentarioIDs (map)
                         |
                         --- "-NKr6..._dyO": true
                         |
                         --- "-NKr6..._dyP": true

No matter what solution you choose, you have to set in the comentarioMap the field according to its type. So it can be either a String, a List, or a Map<String, Any>.

Edit:

According to your last comment:

I need to store in comentarioID the key ending in.... Dyp but it sttores something ending in... Dyo

That's happening because you're calling push() twice. If you want to store the exact same key, then instead of using:

referenciaBD.push().setValue(comentarioMap).addOnCompleteListener() {}
//            👆

Remove push() and use the comentarioID that was generated earlier:

referenciaBD.child(comentarioID).setValue(comentarioMap).addOnCompleteListener() {}
//                  👆

Upvotes: 1

Related Questions