3

I get the Alex Mamo's Solution in order to check whether a unique value exists in my database but the snapshot gets always null. The solution is here:

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) {}
};
userNameRef.addListenerForSingleValueEvent(eventListener);

And my database looks like this:

users
    (auto-generated push token ID)
        fullname
        username
        gender
        ...

I don't know whether it's the right method but I used push() method for adding the user object to the database and this method generates push token ID like above.

So, in order not to create duplicate users, what should I change with the above solution? Is there a better method to do this? Maybe like checking the firebase uid with some firebase auth methods?

UPDATE My database screenshot: database As you see the string just below 'users' is not the same as user's uid.

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
ninbit
  • 530
  • 6
  • 24
  • You get null because you do not have a child called Nick123 `child("Nick123");` as I explained in the second part of my answer. Since you are using randomid instead of userid then check the first part of my answer. – Peter Haddad Aug 09 '18 at 17:49

2 Answers2

5

If you have this database:

users
(auto-generated push token ID)
    fullname
    username
    gender

Then to check if user exists you need to do the following:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userNameRef = rootRef.child("users");
Query queries=userNameRef.orderByChild("fullname").equalTo("Nick123");
ValueEventListener eventListener = new ValueEventListener() {
  @Override
public void onDataChange(DataSnapshot dataSnapshot) {
   if(!dataSnapshot.exists()) {
       //create new user
    }
 }

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

First if you have users lowercase letter, then inside child add users, then you need to use a query to be able to check if the fullname is equal to Nick123.


Usually the database is structured like this:

users
  userId
     fullname: Nick123

The attributes are key:value, the key is the identifier and Nick123 is the value, so inside the child() method you need to write the identifier which is fullname and not Nick123.

Then since you are able to get the userId, you can do this:

FirebaseUser currentFirebaseUser =FirebaseAuth.getInstance().getCurrentUser();
String userId=currentFirebaseUser.getUid();
 DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userNameRef = rootRef.child("users").child(uid).child("fullname");
userNameRef.addValueEventListener(new ValueEventListener(){...}
Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
5

This is not the best practice when it comes to save user details into the database. First, you should implement Firebase Authentication and then in order to check if a user exist in your database, you should use the following lines of code:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("users").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    if(!dataSnapshot.exists()) {
        //create new user
    }
}

    @Override
    public void onCancelled(DatabaseError error) {
        Log.d("TAG",error.getMessage()); //Don't ignore potential errors!
    }
};
uidRef.addListenerForSingleValueEvent(eventListener);

So the key for solving this problem is to call the child() method and pass the UID as an argument instead of calling the push() method that generates an random unique identifier.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • I have already implemented firebase authentication but I needed to store some extra user info. So I saved the user details into the database. So snapshot still gets null with your solution – ninbit Aug 09 '18 at 17:50
  • I added the screenshot of my database – ninbit Aug 09 '18 at 17:53
  • Is `null` and it always be `null` because you are using as unique itenfier the pushed id and not the id provided by Firebase authentication as I adviced you in my answer, right? – Alex Mamo Aug 09 '18 at 17:53
  • And the child is `users` and not `Users`. See capital `U` vs lower case `u`? – Alex Mamo Aug 09 '18 at 17:55
  • But I dont know how to use uid as identifier in the database and I ask you how to do it in the comments – ninbit Aug 09 '18 at 17:56
  • Basically you should use `child(uid)` instead of `push()` method. Basically you should replace the `push()` with `child(uid)`, right? If it is not ok, please add the code that you are using to add the user to the database and I'll show you how, ok? – Alex Mamo Aug 09 '18 at 18:07
  • being newbie around here is hard :) thanks for the patient replies, I didnt know child() method adds the data, just knew setValue() method does this. I think it is better to update your answer with adding this comment for other users – ninbit Aug 09 '18 at 18:36
  • @ninbit `child()` method adds a new child down in your tree, so you're welcome and cheers! – Alex Mamo Aug 09 '18 at 18:37
  • @AndréKool In the solution above, I already have used `.child(uid)` and **not** used the `push()` method. Thanks! – Alex Mamo Aug 09 '18 at 20:23
  • This is only for reading, not writing. OP is using push() to save user info in their question so for this answer to work they will have to change that. – André Kool Aug 09 '18 at 20:25
  • 1
    @AndréKool Ok that's fine. Just updated my answer by adding this info for a better understanding. Thanks André! – Alex Mamo Aug 09 '18 at 20:31