skip to Main Content

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?

2

Answers


  1. try snapshot.getValue<>() and then check if this value is null or not maybe that help

    Login or Signup to reply.
  2. 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") //👈
    

    Where movieIdFromDatabase should be the ID from the database, the one that starts with -.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search