1

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.

Shivam Kumar
  • 1,892
  • 2
  • 21
  • 33
Ujjwal Bassi
  • 51
  • 1
  • 13

3 Answers3

2

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

Joby Wilson Mathews
  • 10,528
  • 6
  • 54
  • 53
Lovekush Vishwakarma
  • 3,035
  • 23
  • 25
  • this works like a charm. Thank you very much! and now i actually understand how this firebase value listenerrs work. – Ujjwal Bassi Dec 04 '17 at 16:55
0

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(",", ".");
}
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • if i make the database as you said, The usernames are like "ujjwal.bassi" with a dot "." and firebase gives an error for that it cannot contain a dot "." and more certain symbols – Ujjwal Bassi Dec 01 '17 at 08:54
  • So the "user_info" : { "-L-7QPKXFyoN-GlPxTTN" : { "email" : "", "name" : "", "password" : "", "username" : "ujjwalbassi" }, "-L-7QPMyzXCqpWT0YLPM" : { "email" : "", "name" : "", "password" : "", "username" : "ujjwalbassi" } } – Ujjwal Bassi Dec 01 '17 at 08:55
  • com.google.firebase.database.DatabaseException: Invalid Firebase Database path: ujjwal.bassi. Firebase Database paths must not contain '.', '#', '$', '[', or ']' – Ujjwal Bassi Dec 01 '17 at 10:28
  • Yes, do the same for each symbol that might be inside the user name and it's forbidden. – Alex Mamo Dec 01 '17 at 10:31
  • the .replace is the (target,replacement); So after all im replacing the "."(dot"),","(comma) that is also forbidden in the username. – Ujjwal Bassi Dec 01 '17 at 10:41
  • Comma is not, only the dot. See this [post](https://stackoverflow.com/questions/31904123/good-way-to-replace-invalid-characters-in-firebase-keys). Does it work now? – Alex Mamo Dec 01 '17 at 11:10
  • And is everything alright? Is working? If you escape those symbols should work. – Alex Mamo Dec 02 '17 at 16:13
  • The code with the orderBychild is working. Where the database ref. is the "user_info" and the orderbychild is "username" it is working. If i have ujjwal.bassi as the username (the db structure is the same as the question didn't change it at all). I've added if else statement too, It shows if the user exists or not but the else part where i've added (if the username.equals(usernamedatabasesend) is not true then the user will be added.The if statement works and the else works with it too. otherwise the logic is working just fine. help? any on why the if else statement isworking at the same time? – Ujjwal Bassi Dec 02 '17 at 16:43
  • The if and the else statement cannot be called in the same time. What is the problem now? – Alex Mamo Dec 04 '17 at 08:22
  • The code in the "OnDataChange" works. But the for statement has to be inside the If statement and the else is normal. Then it will check if the username exists or not and then it will show the result. if it exists it will show the if statement and if it does not exist it will show the else statement – Ujjwal Bassi Dec 04 '17 at 14:57
  • Ok and what is the problem now? – Alex Mamo Dec 04 '17 at 14:58
0

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.

Nathan Bird
  • 910
  • 1
  • 9
  • 23
  • 1
    Yeah so retrieving the whole user_info node will make the app slow and the database / internet work more. – Ujjwal Bassi Dec 01 '17 at 08:56
  • @UjjwalBassi You are correct. That is why I mentioned someone else's answer after properly addressing the specific problem you were having. Good luck with your project! – Nathan Bird Dec 02 '17 at 00:33