0

I have added Firebase to my Android project. I have already created createUserWithEmailAndPassword() to authenticate email and password. Now, I also require username to be stored in Firebase DB while creating a new account.

I have read online, that onAuthenticated(AuthData authData) is used to store username. However, please guide me where to actually place onAuthenticated(AuthData authData) method so that it is called once the email & password authentication is done.

At the moment, I have placed both these methods in private void UserSignUp(), that is called when Sign Up button is clicked. Thanks. Below given is the code:

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

    emailid=(EditText)findViewById(R.id.emailText);
    username=(EditText)findViewById(R.id.usernameText);
    pwd=(EditText)findViewById(R.id.passwordText);
    signup=(Button)findViewById(R.id.signupbutton);

    signup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            UserSignUp();
        }
    });

}

private void UserSignUp()
{
    firebaseAuth = FirebaseAuth.getInstance();

    email = emailid.getText().toString().trim();
    password  = pwd.getText().toString().trim();
    uname = username.getText().toString().trim();

    if (TextUtils.isEmpty(email)) {
        Toast.makeText(getApplicationContext(), "Enter Email address", Toast.LENGTH_SHORT).show();
        return;
    }

    if (TextUtils.isEmpty(password)) {
        Toast.makeText(getApplicationContext(), "Enter password", Toast.LENGTH_SHORT).show();
        return;
    }

    if (TextUtils.isEmpty(uname)) {
        Toast.makeText(getApplicationContext(), "Enter username", Toast.LENGTH_SHORT).show();
        return;
    }

    if (uname.length() < 5) {
        Toast.makeText(getApplicationContext(), "Invalid: Username must be greater than 5 characters", Toast.LENGTH_SHORT).show();
        return;
    }

    if (password.length() < 8) {
        Toast.makeText(getApplicationContext(), "Invalid: Password must be greater than 8 characters", Toast.LENGTH_SHORT).show();
        return;
    }

    firebaseAuth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>()
            {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task)
                {
                    if(task.isSuccessful())
                    {
                        Toast.makeText(SignUpActivity.this,"Successfully registered",Toast.LENGTH_LONG).show();
                    }
                    else
                    {
                        Toast.makeText(SignUpActivity.this,"Registration Error",Toast.LENGTH_LONG).show();
                    }
                }
            });

  Firebase.AuthResultHandler authResultHandler=new Firebase.AuthResultHandler()
    {
        @Override
        public void onAuthenticated(AuthData authData)
        {
            firebaseRef = new Firebase(FIREBASE_URL);

            Map<String, String> map = new HashMap<String, String>();
            map.put("email", email);
            map.put("username", uname);
            map.put("provider", authData.getProvider());

            firebaseRef.child("users").child(authData.getUid()).setValue(map);
        }

        @Override
        public void onAuthenticationError(FirebaseError firebaseError)
        {

        }
    };
}
AL.
  • 36,815
  • 10
  • 142
  • 281
Simran
  • 593
  • 1
  • 14
  • 37
  • Jamie's answer shows the most common approach. See also one of these: [1](http://stackoverflow.com/questions/38442291/firebase-duplicate-username-and-custom-sign-in), [2](http://stackoverflow.com/questions/35243492/firebase-android-make-username-unique), [3](http://stackoverflow.com/questions/37415863/firebase-setting-additional-user-properties), [4](http://stackoverflow.com/questions/25294478/how-do-you-prevent-duplicate-user-properties-in-firebase), [5](http://stackoverflow.com/questions/38442291/firebase-duplicate-username-and-custom-sign-in) – Frank van Puffelen Sep 06 '16 at 14:37

1 Answers1

1

Using your naming as an example:

You would attach the AuthResultHandler named authResultHandler in the onCreate or before you call the createUserWithEmailAndPassword (in onCreate for example). You should also register the auth listener as a field so you are able to reference it later (to deregister).

Firebase.AuthResultHandler authResultHandler=new Firebase.AuthResultHandler()
{ 
    @Override 
    public void onAuthenticated(AuthData authData)
    { 
        firebaseRef = new Firebase(FIREBASE_URL); 

        Map<String, String> map = new HashMap<String, String>();
        map.put("email", email);
        map.put("username", uname);
        map.put("provider", authData.getProvider());

        firebaseRef.child("users").child(authData.getUid()).setValue(map);
    } 

    @Override 
    public void onAuthenticationError(FirebaseError firebaseError)
    { 

    } 
}; 

firebaseAuth.addAuthStateListener(authResultHandler);

You will also need to deregister your listener in onDestroy:

@Override
public void onDestroy() {
    super.onDestroy();
    if (this.firebaseAuth != null) {
        firebaseAuth.removeAuthStateListener(authResultHandler);
    }
}

That should be enough information to get you on the right track.

JamieB
  • 923
  • 9
  • 30