Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search if a username exist in the given firebase database?

{
 users:
  {
    apple:
     {
       username :  apple
       email    :  [email protected]
       uid      :  tyutyutyu
     }
    mango:
     {
       username :  mango
       email    :  [email protected]
       uid      :  erererer
     }
  }
}

This is what I am doing CREATING USER if checkUsername method returns 0

 if(checkFirebaseForUsername(username)==0) {

                    mAuth.createUserWithEmailAndPassword(email, password)
                            .addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
                                @Override
                                public void onComplete(@NonNull Task<AuthResult> task) {
                                    if (task.isSuccessful()) {

                                        Toast.makeText(getBaseContext(),"inside",Toast.LENGTH_LONG).show();
                                        User newUser = new User();
                                        newUser.setUserId(mAuth.getCurrentUser().getUid());
                                        newUser.setUsername(username);
                                        newUser.setEmailId(email);

                                        try{
                                            mRef.child("users").child(username).setValue(newUser);
                                        }
                                        catch(Exception e){
                                            Toast.makeText(SignUpActivity.this,"error while inserting",Toast.LENGTH_LONG).show();
                                        }
                                        AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
                                        builder.setTitle(R.string.signup_success)
                                                .setPositiveButton(R.string.login_button_label, new DialogInterface.OnClickListener() {

                                                    @Override
                                                    public void onClick(DialogInterface dialogInterface, int i) {

                                                        Intent intent = new Intent(SignUpActivity.this, LoginActivity.class);
                                                        startActivity(intent);
                                                        finish();
                                                    }
                                                });
                                        AlertDialog dialog = builder.create();
                                        dialog.show();
                                    } else {
                                        AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
                                        builder.setTitle(R.string.signup_error_title)
                                                .setPositiveButton(android.R.string.ok, null);
                                        AlertDialog dialog = builder.create();
                                        dialog.show();
                                    }
}

My checkUsername method -

public int checkFirebaseForUsername(String passedUsername){
    final int[] flag = {0};
    final String myPassedUsername = passedUsername;
    Log.e("tag","working now");
    //flag[0]=1;

    DatabaseReference mTest = FirebaseDatabase.getInstance().getReference();

       mTest.child("users").child(passedUsername).addChildEventListener(new ChildEventListener() {

        @Override
        public void onDataChanged(DataSnapshot dataSnapshot) {
            Log.e("tag","checking");

            if(dataSnapshot.exists()){
                Log.e("tag","exists");
                flag[0]=1;
               }
         }
        @Override
        public void onCancelled(DataSnapshot datasnapshot){

         }
});




    if(flag[0]==1)
        return 1;
    else
        return 0;
}

This is how I am inserting users in my firebase-database and I want to check if a username is available for a new user or not.

Therefore I need to check is there any user already registered with that username....Please help I have already tried whatever I could understand after reffering to documentation provided on the official firebase blog but all in vain!!

like image 405
Shubham Chauhan Avatar asked Aug 20 '16 10:08

Shubham Chauhan


People also ask

How do you check if a value already exists in Firebase database?

child(busNum). exists() tests for the existence of a value at location BusNumber/<busNum> . It will not be true unless busNum is one of the keys created by push() .

How do I find my database name in Firebase?

You can find your Realtime Database URL in the Realtime Database section of the Firebase console. Depending on the location of the database, the database URL will be in one of the following forms: https:// DATABASE_NAME . firebaseio.com (for databases in us-central1 )

How can I get details from Firebase?

Firebase data is retrieved by either a one time call to GetValueAsync() or attaching to an event on a FirebaseDatabase reference. The event listener is called once for the initial state of the data and again anytime the data changes.


1 Answers

EDIT: New answer, old one still below.

I would get rid of your method "checkFirebaseForUsername" because it will always return 0, no matter what.

What you need to do is this:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("users").child("username").addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
     if(dataSnapshot.exists()){
      // use "username" already exists
      // Let the user know he needs to pick another username.
    } else {
      // User does not exist. NOW call createUserWithEmailAndPassword
      mAuth.createUserWithPassword(...);
      // Your previous code here.

    }                               
  }

  @Override
  public void onCancelled(DatabaseError databaseError) {

  }
});

Old Answer:

{
 users:
  {
    apple[X]:
     {
       username :  apple[Y]
       email    :  [email protected]
       uid      :  tyutyutyu
     }
    mango:
     {
       username :  mango
       email    :  [email protected]
       uid      :  erererer
     }
  }
}

If for example, the node apple[X] will always have the same name as the child property "username":apple[Y], then it is as simple as this.

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("users").child("username").addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
     if(dataSnapshot.exists()){
      // use "username" already exists
    } else {
      // "username" does not exist yet.
    }                               
  }

  @Override
  public void onCancelled(DatabaseError databaseError) {

  }
});

however, if say, the node apple[X] can have a different value than the property apple[Y], and you want to see if any node exists where the "username" property is the same, then you will need to do a query.

 Query query = FirebaseDatabase.getInstance().getReference().child("users").orderByChild("username").equalTo("usernameToCheckIfExists");
 query.addListenerForSingleValueEvent(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.getChildrenCount() > 0) {
            // 1 or more users exist which have the username property "usernameToCheckIfExists"
         }
       }

      @Override
      public void onCancelled(DatabaseError databaseError) {

      }
  });
like image 152
Linxy Avatar answered Sep 22 '22 14:09

Linxy