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

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

问题描述

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

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.

把这个 SO问题作为一个例子,我想知道是否 -JlvccKbEAyoLL9dc9_v 存在。我该怎么做?

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

提前致谢。

推荐答案

这个方法总是类似于我在这个关于JavaScript的答案中写的:测试是否Firebase中存在数据

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) { }
});

但请记住,存在Firebase中的推送ID以防止必须执行此类检查。当多个客户端生成推送ID时,它们在统计上保证是唯一的。因此,他们中的任何一个都无法创建与另一个相同的密钥。

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 Android中是否存在ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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