Ujjwal Bassi
Ujjwal Bassi

Reputation: 61

exist in Firebase database user name

I am trying to search a "username" in firebase database but it always returns the else statement

mDatabaseref = FirebaseDatabase.getInstance().getReference("user_info");

mDatabaseref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.child("username").child(usernamedatabasesend).exists())
        {
            Log.i("USERINFO","USER EXISTS");
        }
        else
        {
            Log.i("USERINFO","USER DOES NOT EXISTS");
        }
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

mDatabaseref = FirebaseDatabase.getInstance().getReference("user_info");
mDatabaseref.push().setValue(uic);

the usernamedatabasesend is the Edittext value to send it to the database to check if that same value the user is entering is existing on the db or not

The Database node is like this

"user_info" : {
    "-L-7QPKXFyoN-GlPxTTN" : {
      "email" : "",
      "name" : "",
      "password" : "",
      "username" : "ujjwalbassi"
    },
    "-L-7QPMyzXCqpWT0YLPM" : {
      "email" : "",
      "name" : "",
      "password" : "",
      "username" : "ujjwalbassi"
    }
}

****UPDATE*********

This is the new code

mDatabaseref.orderByChild("username").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
        {
            userInfo userinfoclass = dataSnapshot1.getValue(userInfo.class);

            String usernamegotunamn = userinfoclass.getUsername().toString();

            if(usernamegotunamn.equals(usernamedatabasesend))
            {
                Log.i("YESONO","USEREXISTS"+"\n"+usernamegotunamn+"\n"+usernamedatabasesend);
            }

            else {
                mDatabaseref.push().setValue(uic);

                Log.i("YESONO", "USERDOESNOTEXIST");
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

The if else is working but if the "IF" is true then else works with it too. but it shows that if the user exists or not.

Upvotes: 1

Views: 931

Answers (3)

Lovekush Vishwakarma
Lovekush Vishwakarma

Reputation: 3169

Try this.

mDatabaseref.orderByChild("username").equalTo("ujjwalbassi").addListenerForSingleValueEvent(
    new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //data will be available on dataSnapshot.getValue();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w(TAG, "getUser:onCancelled", databaseError.toException());
        }
});

Reference : How to Search for data in Firebase Android

Upvotes: 2

Alex Mamo
Alex Mamo

Reputation: 138824

You cannot use exists() method to check whether a value exists or not. If you want to use exists() method, then you should consider change your database structure a little bit. Instead of having as a unique identifier the id that is generated by the push() method, just use the user name. Your database structure should look like this:

"user_info" : {
    "ujjwalbassi" : {
      "email" : "",
      "name" : "",
      "password" : "",
    },
    "anotherUserName" : {
      "email" : "",
      "name" : "",
      "password" : "",
    }
}

The important thing here is, when you add a new user to the database to check the userame for uniqueness. To verify if a user exists, you can use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userNameRef = rootRef.child("user_info").child(usernamedatabasesend);
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if(dataSnapshot.exists()) {
            //do something
        } else {
            //do something else
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
userNameRef.addListenerForSingleValueEvent(eventListener);

Another approach will be to filter the database after usernamedatabasesend and get all the users with the same user name. This is not a good practice, to have users in your database which have the same user name. If you want to go with this, you can use orderByChild() method in a query like this:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query userNameQuery = rootRef.child("user_info").orderByChild("username").equalTo(usernamedatabasesend);
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if(dataSnapshot.exists()) {
            //do something
        } else {
            //do something else
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
userNameQuery.addListenerForSingleValueEvent(eventListener);

If the user name contains a dot ., then you need to encode it in order to use it as a key in the database. To encode the user name please use the following mothod:

static String encodeUserName(String userName) {
    return userName.replace(".", ",");
}

And to get it back, please use the following code:

static String decodeUserName(String userName) {
    return userName.replace(",", ".");
}

Upvotes: 0

Nathan Bird
Nathan Bird

Reputation: 932

To check if the user exists by looping, you'll need to loop through each DataSnapshot and see if the username matches. To do this you need to, first, get a DataSnapshot of all the users, and then loop through each one:

mDatabaseref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot user : dataSnapshot){  
            if(user.child("username").getValue(String.class).equals(usernamedatabasesend)){
                //The username matches!
                Log.i("USERINFO","USER EXISTS");
                return
            }
        }
    }
    @Override public void onCancelled(DatabaseError databaseError) {}
});

This isn't the best practice (Will get slow if you have a ton of users) but it is definitely a working solution. I recommend using @lovekush-vishwakarma's answer as a faster solution.

Upvotes: 0

Related Questions