简体   繁体   English

Firebase Android-检查值是否已经存在

[英]Firebase Android - Check if value is already exists

I need help regarding checking if the value is already exists in the database so Users won't be able to change it to the same number when they're updating it, like a unique ID 我需要检查数据库中是否已存在该值的帮助,以便用户在更新它时无法将其更改为相同的数字,例如唯一ID

I've been searching for hours for a solution but I can't find any that's working. 我一直在寻找解决方案的时间,但找不到任何有效的方法。

ID

To achieve this, I recommend you create another node named userIds . 为此,建议您创建另一个名为userIds节点。 Every time a new user is created just add the user id in this new section. 每次创建新用户时,只需在此新部分中添加用户ID。 This new section should look like this: 这个新部分应如下所示:

Firebase-root
    --- userIds
      --- Id101: true
      --- Id102: true

Then just put a listener on this new node node and use exists() method on the dataSnapshot object. 然后,只需在该新节点节点上放置一个侦听器,并在dataSnapshot对象上使用exist exists()方法即可。

As recommended before you should have a data structure, an index list, for this, why? 按照建议,您应该拥有一个数据结构,一个索引列表,为此,为什么呢? Because when you have tons of this ids it will be a better query. 因为当您拥有大量此类ID时,这将是一个更好的查询。 However, I think what you are trying to do is complementary to the previous suggestions. 但是,我认为您想要做的是对先前建议的补充。

What you have to do is use a single event listener, if the datasnapshot is not null, then the value exists. 您要做的是使用单个事件侦听器,如果datasnapshot不为null,则该值存在。 The key is query the id you need: 关键是查询所需的ID:

DatabaseReference root = FirebaseDatabase.getInstance.getReference();
DatabaseReference reference = root.child("Test").oderByChild("ID").equalsTo(someId);

reference.addSingleValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
       if (dataSnaphot != null) {
       //This means the value exist, you could also dataSnaphot.exist()
       }
    }
    //More auto generated code
);

The dataSnapshot is a bunch of your objects, because the query could match more than one result. dataSnapshot是一堆对象,因为查询可以匹配多个结果。 You can iterate inside of it if you need the value of each: 如果需要每个值,则可以在其中进行迭代:

public void onDataChange(DataSnapshot dataSnapshot) {
           if (dataSnaphot != null) {
           for (DataSnapshot children : dataSnaphot.getChildrens()) {
               YourModel yourModel = children.getValue(YourModel.class);
           }
           }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM