Checking if a particular value exists in the Firebase database

前端 未结 6 1900
孤城傲影
孤城傲影 2020-11-22 07:04

I am making an Android application using Firebase realtime database. When a new user registers on my app, that user\'s data is saved in the Firebase database. <

相关标签:
6条回答
  • 2020-11-22 07:15

    Instead of checking for the exists of the reference you can use orderBy query to check whether username exists already

    orderByChild('username').equalTo(username) query would return data if some data already exists else it will return null.

    0 讨论(0)
  • 2020-11-22 07:18

    To check a existence of user, please use the below code:

    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference userNameRef = rootRef.child("Users").child("Nick123");
    ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(!dataSnapshot.exists()) {
                //create new user
            }
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
        }
    };
    userNameRef.addListenerForSingleValueEvent(eventListener);
    

    You can also use a Query to achieve the same thing like this:

    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    Query query = rootRef.child("Users").orderByChild("userName").equalTo("Nick123");
    query.addValueEventListener(/* ... */);
    

    This is another approach which is looping through the entire Users node but is not just using a direct reference to a single user. This option is more likely to be used when you are using as a unique identifier beteeen users the uid instead of the user name (as you do right now). So if your database structure might looks similar to this:

    Firebase-root
       |
       --- Users
            |
            --- uid
                 |
                 --- userName: "Test User"
                 |
                 --- emailAddress: "user@email.com"
    

    The second solution is the recommended one.

    There is also another solution which involves you to create another node named userNames, in which you can hold only the unique user names. Please also find below the corresponding security rules:

    "Users": {
      "$uid": {
        ".write": "auth !== null && auth.uid === $uid",
        ".read": "auth !== null && auth.provider === 'password'",
        "userName": {
          ".validate": "
            !root.child('userNames').child(newData.val()).exists() ||
            root.child('userNames').child(newData.val()).val() == $uid"
        }
      }
    }
    

    But since in this case, your user name is already the name of the node, I recommend you go ahead with the first one.

    0 讨论(0)
  • 2020-11-22 07:22

    Since you have already got a solution to your problem, I will try to explain why your code was not working.

     DatabaseReference fdbRefer = FirebaseDatabase.getInstance().getReference("Users/"+username);
    

    You might be thinking that in the above statement fdbRefer will be null if "Users/"+username is not present in the database.
    But actually, this statement will only store a path to the specified field in getReference(). So when you check for fdbRef!=null, it is always true because fdbRefer will hold value something like 'https://.firebase.com/Users/Nick123.

    0 讨论(0)
  • 2020-11-22 07:26

    Try this:

    DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Users");
    ref.orderByChild("username").equalTo(Nick123).addValueEventListener(new ValueEventListener(){
      @Override
      public void onDataChange(DataSnapshot dataSnapshot){
          if(dataSnapshot.exist() {
             //username exist
              }
            }
    

    You have to use orderbychild and equalto to check the value if it is there. If you dont use orderbychild and equalto then it will just check if username child node is there and doesnt care about the value.

    this orderByChild("username").equalTo(Nick123) is like saying:

    WHERE username=Nick123
    
    0 讨论(0)
  • 2020-11-22 07:35

    Works Perfectly for me

    DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
            Query query = reference
                    .child(getString(R.string.dbname_users))
                    .orderByChild("username")
                    .equalTo(username);
            query.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if(dataSnapshot.getChildrenCount()>0) {
                        //username found
    
                    }else{
                        // username not found
                    }
    
                }
                @Override
                public void onCancelled(DatabaseError databaseError) {
    
                }
            });
    
    0 讨论(0)
  • Check it like this...

        fdbRefer.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
    if(dataSnapshot.exist() {
    //username exist
    }
    else {
    //username doesn't exist
    }
    }
    });
    
    0 讨论(0)
提交回复
热议问题