Home > database >  Get last child from firebase
Get last child from firebase

Time:05-23

I am trying to add rides to my firebase and I am using the following code:

dbref = FirebaseDatabase.getInstance().getReference("Users")
        databaseQuery = myRef.orderByKey().limitToLast(1)
        firebaseAuth = FirebaseAuth.getInstance()


      databaseQuery.addValueEventListener(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
              var BuleiaId = 0
                for (snapshot in snapshot.children){
                    var viagem = snapshot.getValue(Buleia::class.java)
                    BuleiaId = viagem?.id!!
                }
            }

            override fun onCancelled(error: DatabaseError) {
                TODO("Not yet implemented")
            }
        })

        dbref.addValueEventListener(object : ValueEventListener {

            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot.exists()) {

                    for (userSnapshot in snapshot.children) {
                        val user = userSnapshot.getValue(User::class.java)
                        if (user?.userId == firebaseAuth.currentUser?.uid) {
                            var user = user?.userName
                            button = findViewById(R.id.ButtonAdicionaBoleia)
                            button.setOnClickListener {
                                

                                var id = BuleiaId 1
                                var rideDay = findViewById<EditText>(R.id.rideDay).text
                                var rideTime = findViewById<EditText>(R.id.rideTime).text
                                var driveFrom = findViewById<EditText>(R.id.driveFrom).text
                                var driveTo = findViewById<EditText>(R.id.driveTo).text
                                var pick1 = findViewById<EditText>(R.id.pickUp_1).text
                                var pick2 = findViewById<EditText>(R.id.pickUp_2).text
                                var pick3 = findViewById<EditText>(R.id.pickUp_3).text

                                /*val sharedPref = this.getPreferences(Context.MODE_PRIVATE)
                                val user_id = sharedPref.getString("user_id", "anonimo")*/
                                //var user = FirebaseAuth.getInstance().currentUser?.uid
                                val buleia = Buleia(
                                    id,
                                    rideDay.toString(),
                                    rideTime.toString(),
                                    driveFrom.toString(),
                                    driveTo.toString(),
                                    pick1.toString(),
                                    pick2.toString(),
                                    pick3.toString(),
                                    user.toString()
                                )
                                myRef.child(id.toString()).setValue(buleia)
                                buleiaCreated()
                                // myRef.setValue(buleia)
                            }
                        }
                    }
                }
            }
            override fun onCancelled(error: DatabaseError) {

            }
        })

    }

How can I pass the values to the second firebase request? Or merge both toguether? I need the username from the table Users but I need the child from the table Buleia. The problem currently is that when creating new value Buleia is writting on the current one, I want to check the last Id on database that have been created so I can create a diferent ID

CodePudding user response:

dbref = FirebaseDatabase.getInstance().getReference("Users")
databaseQuery = myRef.orderByKey().limitToLast(1)
firebaseAuth = FirebaseAuth.getInstance()


databaseQuery.addValueEventListener(object : ValueEventListener {
    override fun onDataChange(snapshot: DataSnapshot) {
        var BuleiaId = 0
        for (snapshot in snapshot.children){
            var viagem = snapshot.getValue(Buleia::class.java)
            BuleiaId = viagem?.id!!
        }
        dbref.addValueEventListener(object : ValueEventListener {

            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot.exists()) {

                    for (userSnapshot in snapshot.children) {
                        val user = userSnapshot.getValue(User::class.java)
                        if (user?.userId == firebaseAuth.currentUser?.uid) {
                            var user = user?.userName
                            button = findViewById(R.id.ButtonAdicionaBoleia)
                            button.setOnClickListener {


                                var id = BuleiaId 1
                                var rideDay = findViewById<EditText>(R.id.rideDay).text
                                var rideTime = findViewById<EditText>(R.id.rideTime).text
                                var driveFrom = findViewById<EditText>(R.id.driveFrom).text
                                var driveTo = findViewById<EditText>(R.id.driveTo).text
                                var pick1 = findViewById<EditText>(R.id.pickUp_1).text
                                var pick2 = findViewById<EditText>(R.id.pickUp_2).text
                                var pick3 = findViewById<EditText>(R.id.pickUp_3).text

                                /*val sharedPref = this.getPreferences(Context.MODE_PRIVATE)
                                val user_id = sharedPref.getString("user_id", "anonimo")*/
                                //var user = FirebaseAuth.getInstance().currentUser?.uid
                                val buleia = Buleia(
                                    id,
                                    rideDay.toString(),
                                    rideTime.toString(),
                                    driveFrom.toString(),
                                    driveTo.toString(),
                                    pick1.toString(),
                                    pick2.toString(),
                                    pick3.toString(),
                                    user.toString()
                                )
                                myRef.child(id.toString()).setValue(buleia)
                                buleiaCreated()
                                // myRef.setValue(buleia)
                            }
                        }
                    }
                }
            }
            override fun onCancelled(error: DatabaseError) {

            }
        })
    }

    override fun onCancelled(error: DatabaseError) {
        TODO("Not yet implemented")
    }
})
}

I am not aware about your logic but here it is what I am telling you

CodePudding user response:

First, make sure that you are using correct scope for your BuleiaId variable. Second, you can call either get or addListenerForSingleValueEvent for single fetch scenarios then you can add your second query by nesting into first one .

   databaseQuery.addListenerForSingleValueEvent(object : ValueEventListener {
        override fun onDataChange(snapshot: DataSnapshot) {
          var BuleiaId = 0
            for (snapshot in snapshot.children){
                var viagem = snapshot.getValue(Buleia::class.java)
                BuleiaId = viagem?.id!!
                //your second query with BuleiaId  
            }
        }

        override fun onCancelled(error: DatabaseError) {
            TODO("Not yet implemented")
        }
    })

using get() :

  databaseQuery.get().addOnSuccessListener{
      snapshot ->
      var BuleiaId = 0
        for (snapshot in snapshot.children){
            var viagem = snapshot.getValue(Buleia::class.java)
            BuleiaId = viagem?.id!!
            //your second query with BuleiaId  
        }
   }

you can also use push() that auto generate 120bits unique ids if it suits your logic.

  • Related