0

I want to write data in my Firebase database. But there should be a check if the email, username and userID are already exists.

I have found something similar. But I don't understand the code.

Firebase android : make username unique

Can you help me by this problem?

Thank you very much.

1 Answers1

0

The given database structure is used to store user details such as username, name and job. user1 is a username.

{
 "users" : {
    "user1" : {
       "job" : "developer",
       "name" : "abc"
     }
   }
}

To use firebase in an activity:

Firebase.setAndroidContext(this);
final Firebase ref = new Firebase("firebase_url");

Let uName be a String to store username accepted from the user.

String uNAme;

To check if a given user exists

ref.child("users").child(uName).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if(dataSnapshot.exists()){
              //username is present in the database
        }else{
           //username is not present in the databse
        }
    }

    @Override
    public void onCancelled(FirebaseError firebaseError)
    {
      //in onCancelled
    }
 });

Similarly other values like email, etc can be checked inside onDataChange.

dataSnapshot.exists()

returns true in the above code snippet if a user is present with a username as the one inside the uName.

You can even use addListenerForSingleValueEvent instead of addValueEventListener

Joseph Varghese
  • 589
  • 5
  • 16