[英]Firebase check item if exist
I'm saving an id to Firebase Realtime Database like this:我将 id 保存到 Firebase 实时数据库,如下所示:
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.我需要检查这个id是否存在于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?
我在哪里做错了?
try snapshot.getValue<>()
and then check if this value is null or not maybe that help尝试
snapshot.getValue<>()
然后检查这个值是否是 null 或者不是可能有帮助
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.它检查
movie
节点是否存在,而不是特定电影。 Since under that node, most likely there are multiple movies, snapshot.exists()
will always return true.由于在该节点下,很可能有多个电影,
snapshot.exists()
将始终返回 true。 If you want to check the existence of a particular movie, you need to add the corresponding ID to the reference:如果要检查特定电影是否存在,则需要在引用中添加相应的 ID:
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 -
.其中
movieIdFromDatabase
应该是数据库中的 ID,即以-
开头的 ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.