如何搜索给定的Firebase数据库中是否存在用户名? [英] How to search if a username exist in the given firebase database?

查看:40
本文介绍了如何搜索给定的Firebase数据库中是否存在用户名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

{
 users:
  {
    apple:
     {
       username :  apple
       email    :  apple@xy.com
       uid      :  tyutyutyu
     }
    mango:
     {
       username :  mango
       email    :  mango@xy.com
       uid      :  erererer
     }
  }
}

这就是我在做什么 如果checkUsername方法返回0,则创建用户

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();
                                    }
}

我的checkUsername方法-

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;
}

这是我在 firebase数据库中插入用户的方式,我想检查用户名是否可用于新用户.

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.

因此,我需要检查是否有已经使用该用户名注册的用户....请帮助我,在参考Firebase官方博客上提供的文档之后,我已经尝试了所有我能理解的内容,但是一切都是徒劳的!

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!!

推荐答案

新答案,旧答案仍在下面.

New answer, old one still below.

我将摆脱方法"checkFirebaseForUsername",因为无论如何它总是返回0.

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

您需要做的是这样

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) {

  }
});

旧答案:

{
 users:
  {
    apple[X]:
     {
       username :  apple[Y]
       email    :  apple@xy.com
       uid      :  tyutyutyu
     }
    mango:
     {
       username :  mango
       email    :  mango@xy.com
       uid      :  erererer
     }
  }
}

例如,如果节点apple [X]始终与子属性"username":apple [Y]具有相同的名称,那么就这么简单.

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) {

  }
});

但是,如果说,节点apple [X]可以具有与属性apple [Y]不同的值,并且您想查看是否存在"username"属性相同的任何节点,那么您将需要进行查询.

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) {

      }
  });

这篇关于如何搜索给定的Firebase数据库中是否存在用户名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆