简体   繁体   English

Firebase 用户注册/用户名身份验证

[英]Firebase User Registration / Authentication with Username

Im very new new to Firebase and Im creating my first app.我是 Firebase 的新手,我正在创建我的第一个应用程序。

Im having 2 issues that I would like to get some help please.我有 2 个问题,我想得到一些帮助。

I have linked my Android Studio application to my Firebase project and created the code for the Sigup of new user.我已将我的 Android Studio 应用程序链接到我的 Firebase 项目,并为新用户的 Sigup 创建了代码。

SignupActivity.java注册活动.java

    package com.company.fbaseapp.activities;

    import android.content.Intent;
    import android.support.annotation.NonNull;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.WindowManager;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ProgressBar;
    import android.widget.Toast;

    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
    import com.google.firebase.auth.AuthResult;
    import com.google.firebase.auth.FirebaseAuth;
    import com.company.fbaseapp.R;

    public class SignupActivity extends AppCompatActivity {

        private static final String TAG = "SignupActivity";

        private EditText mUsername;
        private EditText mEmail;
        private EditText mPassword;

        private Button mSignup;

        private ProgressBar mProgressBar;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_signup);

            //mUsername = (EditText) findViewById(R.id.input_username);

            mEmail = (EditText) findViewById(R.id.input_email);
            mPassword = (EditText) findViewById(R.id.input_password);
            mSignup = (Button) findViewById(R.id.btn_signup);

            mSignup.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {

                    Log.d(TAG, "onClick: attempting to signup.");

                    // Check for null valued EditText fields
                    if (!isEmpty (mEmail.getText().toString()) && !isEmpty (mPassword.getText().toString())) {

                        signupNewUser(mEmail.getText().toString(), mPassword.getText().toString());

                        //Toast.makeText(SignupActivity.this, "Thank you for signing up", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        Toast.makeText(SignupActivity.this, "You must fill out all the fields", Toast.LENGTH_SHORT).show();
                    }

                }

            } );

            hideSoftKeyboard();

        }

        private void signupNewUser(String email, String password) {

            showDialog();

            FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
                    .addOnCompleteListener( new OnCompleteListener<AuthResult>() {

                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {

                            Log.d(TAG, "onComplete: onComplete: " + task.isSuccessful());

                            if (task.isSuccessful()) {

                                Log.d(TAG, "onComplete: AuthState: " + FirebaseAuth.getInstance()
                                        .getCurrentUser()
                                        .getUid());

FirebaseUser currentperson=FirebaseAuth.getInstance().getCurrentUser();
                            DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Users").child(currentperson.getUid());
                            ref.child("Username").setValue(name);

                                FirebaseAuth.getInstance().signOut();

                                redirectLoginScreen();

                            }
                            if (!task.isSuccessful()) {

                                Toast.makeText(SignupActivity.this, "Unable to signup", Toast.LENGTH_SHORT).show();

                            }

                        }

                    });

        }

        /**
         * Return true if the @param is null
         * @param string
         * @return
         */
        private boolean isEmpty(String string){
            return string.equals("");
        }

        /**
         * Redirects the user to the login screen
         */
        private void redirectLoginScreen(){
            Log.d(TAG, "redirectLoginScreen: redirecting to login screen.");

            Intent intent = new Intent(SignupActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }

        private void showDialog(){
            mProgressBar.setVisibility(View.VISIBLE);

        }

        private void hideDialog(){
            if(mProgressBar.getVisibility() == View.VISIBLE){
                mProgressBar.setVisibility(View.INVISIBLE);
            }
        }

        private void hideSoftKeyboard(){
            this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        }

    }

LogCat日志猫

12-30 01:19:18.492 31917-31917/com.company.fbaseapp D/SignupActivity: onClick: attempting to signup.
12-30 01:19:18.493 31917-31917/com.company.fbaseapp D/AndroidRuntime: Shutting down VM
12-30 01:19:18.497 31917-31917/com.company.fbaseapp E/AndroidRuntime: FATAL EXCEPTION: main

Process: com.company.fbaseapp, PID: 31917
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference
at com.company.fbaseapp.activities.SignupActivity.showDialog(SignupActivity.java:126)
at com.company.fbaseapp.activities.SignupActivity.signupNewUser(SignupActivity.java:72)
at com.company.fbaseapp.activities.SignupActivity.access$300(SignupActivity.java:21)
at com.company.fbaseapp.activities.SignupActivity$1.onClick(SignupActivity.java:54)
at android.view.View.performClick(View.java:6289)
at android.view.View$PerformClick.run(View.java:24800)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6809)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
12-30 01:19:18.499 31917-31917/com.company.fbaseapp D/AppTracker: App Event: crash

The first issue is that the application is crashing when I click on the mSignup button.第一个问题是当我单击mSignup按钮时应用程序崩溃。

Thesecond issue is that I would like to know how I can add a Unique Username to each registerd user.第二个问题是我想知道如何为每个注册用户添加唯一用户名。

Please help me figure out how to fix these 2 issues.请帮我弄清楚如何解决这两个问题。

在此处输入图片说明

Thanks谢谢

This is the error:这是错误:

`Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference`

the progressbar is null, you need to add this:进度条为空,您需要添加以下内容:

mProgressBar = (ProgressBar) findViewById(R.id.progressBar); //your id in xml

Regarding unique username for each user, you can do this:关于每个用户的唯一用户名,您可以这样做:

 FirebaseUser currentperson=FirebaseAuth.getInstance().getCurrentUser();

then if you are saving to the database, you can do this:那么如果你要保存到数据库,你可以这样做:

      DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Users");
   ref.child(currentperson.getUid());

The above will add a unique userid to each username.以上将为每个用户名添加一个唯一的用户 ID。

If you mean to add a unique username in authentication, you cannot do that.如果您想在身份验证中添加唯一的用户名,则不能这样做。 But the email is unique there by default so if you try to register another user with same email then you will get error:authentication failed但是默认情况下电子邮件在那里是唯一的,因此如果您尝试使用同一电子邮件注册另一个用户,那么您将收到error:authentication failed

Edit:编辑:

You cannot add username in authentication, if you go to the console then you will see the userid and email there added.您不能在身份验证中添加username ,如果您转到控制台,您将看到添加的useridemail The authentication provides you with a userid but username cannot be added in the authentication, it can only be added in the database, can do this:认证给你提供了一个userid但是userid不能在认证中添加,只能在数据库中添加,可以这样做:

     DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Users").child(currentperson.getUid());
   ref.child("Username").setValue(name);

then in your firebase database you would have this:然后在您的 firebase 数据库中,您将拥有:

    Users
         LA0rRvP4TrewYbMSl0bDA3ork8h2
                    Username: hisname_here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM