I'm saving an id to Firebase Realtime Database like this:
binding.ivStar.setOnClickListener {
firebaseDb.getReference("Users").child(uid).child("movie").push()
.setValue(args.movie?.id)}
And I need to check if this id exists in Firebase. And I did like this:
private fun checkData() {
val postRef = firebaseDb.getReference("Users").child(uid).child("movie")
postRef.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
Log.e("Fragment", "${args.movie?.title} exists")
} else {
Log.e("Fragment", "${args.movie?.title} not exists")
}
}
override fun onCancelled(error: DatabaseError) {
Log.e("Fragment", error.toString())
}
})
}
Every time I check, it returns movie exists even if I don't save it. Where am I doing wrong?
CodePudding user response:
try snapshot.getValue<>()
and then check if this value is null or not maybe that help
CodePudding user response:
every time I check, it returns a movie exists even if I don't save it.
This is happening because when you attach a listener to the following reference:
val postRef = firebaseDb.getReference("Users").child(uid).child("movie")
It checks if the movie
node exists, and not a particular movie. Since under that node, most likely there are multiple movies, snapshot.exists()
will always return true. If you want to check the existence of a particular movie, you need to add the corresponding ID to the reference:
val postRef = firebaseDb.getReference("Users")
.child(uid)
.child("movie")
.child("movieIdFromDatabase") //