How to replace autogenerated firebase node id to the current user email - android

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)

Related

Not able to create users under the admin firebase user using standard firebase as It's kicked off the current user

No error message but it will kick off the current logged in user and make the newly created user the current logged in user for example If A creates new user B then B becomes current logged in user.
if (password.equals(confirmpassword)){
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(AddUserActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressbar.setVisibility(View.GONE);
if (task.isSuccessful()) {
user userinfo = new user(
firstname,
lastname,
email,
type,
adminkey
);
FirebaseDatabase.getInstance().getReference("AdminUsers")
.child(Objects.requireNonNull(FirebaseAuth.getInstance().getUid()))
.setValue(userinfo)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(AddUserActivity.this, "Email sent", Toast.LENGTH_SHORT).show();
}
Toast.makeText(AddUserActivity.this, "Registration completed", Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(AddUserActivity.this, "User already exist", Toast.LENGTH_SHORT).show();
}
// ...
}
});

Firebase user's email address method updateEmail is not working correctly

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.

Switch between Users in FirebaseUser - FirebaseAuth

I've been working on an Admin Control panel on Android. inside which admin can add and disable the users.
Suppose the admin uid is I4YnygVk2eaCLEJbCiCLiWlo13as
mAuth.createUserWithEmailAndPassword(emailid, password)
.addOnCompleteListener(UserManagement.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful()+"uid"+mAuth.getCurrentUser().getUid());
//here the Uid is changed to the new registered user i.e RlhiQxMibWYA1NaqlN9JdFZ8ocK2.
AuthCredential credential = EmailAuthProvider
.getCredential("a#a.com", "123456");
firebaseUser.reauthenticate(credential)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
//here what i need is getUid() should print the admin's uid(I4YnygVk2eaCLEJbCiCLiWlo13as), and not the newly created uid.
Log.d(TAG, "User re-authenticated."+firebaseUser.getUid()) database.getReference("users/"+mAuth.getCurrentUser().getUid()).child("active").setValue(true);
}
});
}
});
When your user creation is successful call this method
FirebaseAuth.getInstance().signOut();
this would signout the newly created user and then you can signin with admin credentials.

Create new user with Names , Username etc in firebase

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

Firebase Authentication - How to delete user account using their emails?

Can I delete not authenticated user's account? The docs offers such a way:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.delete()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User account deleted.");
}
}
});
Is this the only way to delete account?

Categories

Resources