I'm new android learner so its is difficult for me to do stuffs which I cannot find in the documentation. Here is my code for creating users
mAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//Successfully Registered
Toast.makeText(RegisterActivity.this, "Registration Successful", Toast.LENGTH_SHORT).show();
}else {
//Error occurred during registration
Toast.makeText(RegisterActivity.this, "Registration Unsuccessful", Toast.LENGTH_SHORT).show();
try {
throw task.getException();
} catch(FirebaseAuthWeakPasswordException e) {
editTextPassword.setError(e.getMessage());
editTextPassword.requestFocus();
}catch(FirebaseAuthUserCollisionException | FirebaseAuthInvalidCredentialsException e) {
editTextEmail.setError(e.getMessage());
editTextEmail.requestFocus();
} catch(Exception e) {
Log.e(RegisterActivity.class.getName(), e.getMessage());
}
}
progressDialog.dismiss();
}
});
This only takes two parameters(email and password) to create an user. To create user with more fields what approach should I take.
I have also added a FirebaseAuth.AuthStateListener() to check user login status. But when I'm calling firebaseAuth.getCurrentUser().getDisplayName() after successfully user login it returns null as usual.So how can I create user with Names so I can retrieve it with firebaseAuth.getCurrentUser().getDisplayName().
After the registration is successful,
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName("Jane Q. User")
.build();
EDIT: This code is a bit incomplete as profileUpdates is never accessed.
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User profile updated.");
}
}
});
Then, to retrieve it, use this wherever required,
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// Name, email address etc
String name = user.getDisplayName();
String email = user.getEmail();
}
To add a user with extra information such as User's name or other required information you should store these data using the Firebase real-time database under the unique user_id generated upon successful completion of email and password registration.
Get user input for name in registration form,
String name = mNameField.getText().toString().trim();
Add user's name in onComplete method :
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
String user_id = mAuth.getCurrentUser().getUid;
DatabaseReference current_user = mDatabase.child(user_id);
current_user.child("name").setValue(name);
progressDialog.dismiss();
}
Related
I'm trying to replace autogenerated firebase node id to the current user email please check code below, I'm using firebase realtime database
Code:
mAuth.createUserWithEmailAndPassword(demail, dpass)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
User user = new User(dname, demail, dcontact, dcity, dage);
FirebaseDatabase.getInstance().getReference("doctors")
.child("Doctors_Registration")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(signup.this, "Doctor Registered", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
} else {
Toast.makeText(signup.this, "Failed to Registered, Try Again!" + task.getException(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
The key of the node is determined by this code:
FirebaseDatabase.getInstance().getReference("doctors")
.child("Doctors_Registration")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()) // 👈
.setValue(user)
So you're using the user's UID as the key for their node.
If you want to use the user's email you can use that instead of the UID. The only thing you'll need to take care of is to remove any . from the email address, as those are not a valid character in keys in the database.
So you could do:
FirebaseDatabase.getInstance().getReference("doctors")
.child("Doctors_Registration")
.child(email.replace(".", ",")) // 👈
.setValue(user)
I also used the re-authentication method before using before the updateEmail method. Everything working correctly. Even the toast message in the updateEmail also appears as expected but there is no change in the firebase database of the user.
It detects the already existed email in the firebase database and show a toast of "Email already exist".
It also works fine in checking the email from firebase and if it doesn't collide then it shows a toast message "Email upadated".
But still it doesn't change the email in the firebase database.
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
// Get auth credentials from the user for re-authentication. The example below shows
// email and password credentials but there are multiple possible providers,
// such as GoogleAuthProvider or FacebookAuthProvider.
AuthCredential credential = EmailAuthProvider
.getCredential(mAuth.getCurrentUser().getEmail(), password);
// Prompt the user to re-provide their sign-in credentials
user.reauthenticate(credential)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User re-authenticated.");
mAuth.fetchSignInMethodsForEmail(email.getText().toString()).addOnCompleteListener(new OnCompleteListener<SignInMethodQueryResult>() {
#Override
public void onComplete(#NonNull Task<SignInMethodQueryResult> task) {
if (task.isSuccessful()) {
try {
if (task.getResult().getSignInMethods().size() == 1) {
Log.d(TAG, "onComplete: This will return the signin methods");
Toast.makeText(getActivity(), "The email is already exist", Toast.LENGTH_SHORT).show();
}else{
Log.d(TAG, "onComplete: Email is not present. User can change it");
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.updateEmail(email.getText().toString())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User email address updated.");
Toast.makeText(getActivity(), "The email updated.", Toast.LENGTH_SHORT).show();
}
}
});
}
}catch(NullPointerException e) {
Log.e(TAG, "onComplete: NullPointerException" + e.getMessage());
}
}
}
});
} else {
Log.d(TAG, "onComplete: User re-authentication failed.");
}
}
});
This mAuth.getCurrentUser().getEmail() will give you the email from the Firebase built-in user class and not from the database itself.
And I cant see any way that you have changed the email in the database itself.
This function updates the email in the Firebase user class which can be seen in the "Authentication" section of your Firebase console
user.updateEmail(email.getText().toString())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User email address updated.");
Toast.makeText(getActivity(), "The email updated.", Toast.LENGTH_SHORT).show();
}
}
});
To update the data in database you have to follow this
Once again I am repeating you are updating the email of a user in the Firebase user class not the actual database. As mentioned, updated email will only be visible in "Authentication" section of Firebase console and to make data change in "database" you have to follow the link.
In my project only Admin can add user to firebase.
At the time of creation i want to get user id because i want to set up profile of that user in Firebase Database.
public void addNewFaculty(View view){
String name,email,password,rePassword;
name = txtname.getText().toString();
email = txtEmail.getText().toString().trim();
password = txtPassword.getText().toString().trim();
rePassword = txtRepassword.getText().toString().trim();
if(password.equals(rePassword))
{
Toast.makeText(this, "Password is not match", Toast.LENGTH_SHORT).show();
return;
}
databaseReference= FirebaseDatabase.getInstance().getReference();
firebaseUser = firebaseAuth.getCurrentUser();
String id= firebaseUser.getUid();
databaseReference = databaseReference.child("Profile").child(id);
databaseReference.child("Name").setValue(name);
// and some other things
firebaseAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(), "Employee Added Successfully", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Please try Again", Toast.LENGTH_SHORT).show();
}
}
});
}
And my firebase structure is
And my firebase structure is given below. I want to get user id at the time of user creation
Here is my Firebase Auth Image
And want to set id here
When You create a user in firebase auth, it automatically log in. Therefore you can get your id in onComplete(), if method as:
if(task.isSuccessful()){
String id1 = firebaseAuth.getCurrentUser().getUid();
//For adding into database
databaseReference = databaseReference.child("Profile").child(id1);
databaseReference.child("Name").setValue(name);
Toast.makeText(getApplicationContext(), "Employee Added Successfully", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Please try Again", Toast.LENGTH_SHORT).show();
}
#Himashu Nain's answer is not correct for this question. firebaseAuth.getCurrentUser().getUid(); will get the Admin's userId since the Admin is logged in and is the current user.
#AtifRizwan wants the userId of the employee account created(not the Admin's!). To get the user id of the account created, You can get the user information from the task returned by the completion listener: i.e
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());
if (task.isSuccessful()) {
FirebaseUser user = task.getResult().getUser();
Log.d(TAG, "onComplete: uid=" + user.getUid());
}
}
});
I am creating a project with firebase for login screen. I am trying to update the displayName of user with the code below but it is not updating the display name. Help me out
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(name)
.build();
user.updateProfile(profileUpdates).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(VerifyUser.this,"Name updated successfully",Toast.LENGTH_LONG).show();
startActivity(new Intent(VerifyUser.this,MainActivity.class));
}else
Toast.makeText(VerifyUser.this,"Name update Failed",Toast.LENGTH_LONG).show();
}
});
You need to update the user profile right after a log-in or a verification of email and password.
I know I am late, but for posterity, for one to update a user attributes on firebase, they need to login first.
so something like :
mAuth.signInWithCredential(credential)
.addOnCompleteListener(LordRegister.this,
new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//verification successful we will start the profile activity
FirebaseUser user = task.getResult().getUser();
String name = nameInput.getText().toString().trim();
//user.updateProfile()
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(name)
.build();
user.updateProfile(profileUpdates).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Intent intent = new Intent(LordRegister.this, LordHome.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}else
Toast.makeText(LordRegister.this,"Name update Failed, try again",Toast.LENGTH_LONG).show();
}
});
} else {
//verification unsuccessful.. display an error message
String message = "Somthing is wrong, we will fix it soon...";
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
message = "Invalid code entered...";
}
Toast.makeText(LordRegister.this,message,Toast.LENGTH_SHORT).show();
}
}
});
}
Like above I'm using a user phoneNumber to sign-in or rather to verify a user first, then updating the name or any other attribute.
I'm trying to create an profile activity, where users can change those Profile picture and Display name, I'm trying to update user photo or user name, CompleteListener called, task.isSuccessful = true but nathing done, why?
Function to update name:
FirebaseUser mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final String newName;
newName = input.getText().toString();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(newName)
.build();
mFirebaseUser.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
DatabaseReference mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference().child("users");
mFirebaseDatabaseReference.child(mFirebaseUser.getUid()).child("DisplayName").setValue(newName);
updateUI();
Toast.makeText(ProfileActivity.this, "User display name updated.", Toast.LENGTH_SHORT).show();
} else
Toast.makeText(ProfileActivity.this, "Error while updating display name.", Toast.LENGTH_SHORT).show();
}
});
Same when i'm trying to update Profile picture that I just uploaded to Firebase Storage...
And idea?
EDIT:
Sometimes the username really get updated, I think it's take like more then 10 minutes to update, why?
I have had a similar problem where the User information was not updating until the User re-authenticated. I resolved it by also saving this information in my firebase database. For me this made sense, as I wanted Users to be able to get basic information about other Users anyway.
My code ended up looking something like this. When the account is created, or modified, I made a call to the "users/{uid}" endpoint and updated the object there. From here I used the GreenRobot EventBus to send my new User object to whoever was subscribed so that it would be updated on the screen.
private FirebaseUser firebaseUser;
public void createUser(String email, String password, final User user, Activity activity, final View view) {
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(activity, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());
// If sign in fails, display a messsage to the user. If sign in successful
// the auth state listener will be notified and logic to handle
// signed in user can be handled in the listener
if (!task.isSuccessful()) {
Snackbar.make(view, task.getException().getLocalizedMessage(), Snackbar.LENGTH_SHORT).show();
} else {
firebaseUser = task.getResult().getUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(user.displayName)
.build();
firebaseUser.updateProfile(profileUpdates);
updateDatabase(user);
EventBus.getDefault().post(new LoginEvent());
}
}
});
}
public boolean updateDatabase(User user) {
if (firebaseUser == null) {
Log.e(TAG, "updateDatabase:no currentUser");
return false;
}
return userReference.setValue(user).isSuccessful();
}
The setup of the database watcher was done something like this. Note that you need to make sure that you remove the listener when the User logs out and add a new one when the User logs in.
protected void setupDatabaseWatcher() {
String uid = firebaseUser.getUid();
userReference = FirebaseDatabase.getInstance().getReference("users/" + uid);
userReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
User user = dataSnapshot.getValue(User.class);
Log.d(TAG, "Value is: " + user);
EventBus.getDefault().post(new UserUpdateEvent(user));
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
Use this simple code:
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(newName)
.build();