检查Firebase中是否存在ID Android [Java] [英] Check if ID exists in Firebase Android [Java]

查看:208
本文介绍了检查Firebase中是否存在ID Android [Java]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个android应用程序,我想检查一个键是否存在,以避免重复的值。我一直在调查,但是看起来我可以添加的是听众,当我只想检查一个ID是否存在。



取这个 SO问题为例,我想知道 -JlvccKbEAyoLL9dc9_v 存在。



我该如何做?



提前感谢。

  ref。 child( -  JlvccKbEAyoLL9dc9_v)addListenerForSingleValueEvent(new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot snapshot){
if(snapshot.exists()){
// TODO:处理数据已经存在的情况
}
else {
// TODO:处理数据尚不存在的情况
}
}

@Override
public void onCancelled(FirebaseError firebaseError){}
});

但是请记住,Firebase中的push id存在,以防止进行这种检查。当多个客户端生成推送ID时,它们在统计上保证是唯一的。因此,没有其他人可以创建与另一个相同的键。



任何情况下,你需要检查一个项目是否已经存在可能有竞争条件:if两个客户几乎在同一时间执行此检查,他们都不会找到值。


I am writing an android app and I want to check if a key exists in order to avoid duplicate values. I´ve been investigating but it looks that all I can add is listeners, when I just want to check if an ID exists or not already.

Taking this SO question as an example, I would like to know if -JlvccKbEAyoLL9dc9_v exists.

How can I do this?

Thanks in advance.

解决方案

The approach will always be similar to what I wrote in this answer about JavaScript: Test if a data exist in Firebase

ref.child("-JlvccKbEAyoLL9dc9_v").addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot snapshot) {
    if (snapshot.exists()) {
      // TODO: handle the case where the data already exists
    }
    else {
      // TODO: handle the case where the data does not yet exist
    }
  }

  @Override
  public void onCancelled(FirebaseError firebaseError) { }
});

But keep in mind that push ids in Firebase exist to prevent having to do this sort of check. When multiple clients generate push ids, they are statistically guaranteed to be unique. So there's no way one of them can create the same key as another.

Any case where you need to check if an item already exists is likely to have race conditions: if two clients perform this check almost at the same time, neither of them will find a value.

这篇关于检查Firebase中是否存在ID Android [Java]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆