When i am creating new account its name equals users UID is there anyway to change it to custom name?
My code
mAuth.createUserWithEmailAndPassword(Email, Password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
User user = new User(Name, LastName, Email);
curentUser = Name + " " + LastName;
FirebaseDatabase.getInstance().getReference("No server")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "User has been registered successfully!", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this,"Failed to register! try again!", Toast.LENGTH_LONG).show();
}
}
});
}else{
Toast.makeText(MainActivity.this,"Failed to register! try again!", Toast.LENGTH_LONG).show();
}
}
});
How it looks like
You can't change the key of an existing value in Firebase Realtime Database without reading the value, write it under a new key, and delete the old one.
That being said, you chose the key of the user object yourself:
FirebaseDatabase
.getInstance().getReference()
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user)
The child method contains the key for the value you set in setValue. And you use the current user's UID for this.
You can change this to whatever value you like. For example, you could the user's email as a key (see reference for current user object):
.child(FirebaseAuth.getInstance().getCurrentUser().getEmail())
Note: See the comment from #puf below, you might want to encode an email address when using as a key.
Related
I am trying to be able to register users into my database.
After I register the users they are being added to my firebase authentication which is great but nothing is changed in my Realtime Database.
It's worth mentioning that my Firebase location isn't in the US.
I have tried many different things:
Put the firebase link inide of the "getInstance()"
Replace the current google-services file with an updated one, including the Firebase's link inside of it
use getReferenceFromUrl() with the firebase's link inside of it.
None of those seemed to work.
Main part of the code in which I'm trying to register the user:
mAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
User user = new User(name, email, password);
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(RegisterUser.this, "User Registered", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(RegisterUser.this, "Failed to register user", Toast.LENGTH_SHORT).show();
}
}
});
}else{
Toast.makeText(RegisterUser.this, "Failed to register user", Toast.LENGTH_SHORT).show();
}
}
});
These are the Realtime Database rules:
{
"rules": {
".read": "true",
".write": "true"
}
}
It's worth noting that I have tried everything I found, including an answer to the same question in this site. Unfortunately none seem to work for me so I had to ask to understand the issue.
Thanks.
I want to check when a user attempts to signup with createUserWithEmailAndPassword() in Firebase user Authentication method, this user is already registered with my app.
To detect whether a user with that email address already exists, you can detect when the call to createUserWithEmailAndPassword () fails with auth/email-already-in-use. I see that #Srinivasan just posted an answer for this.
Alternatively, you can detect that an email address is already used by calling fetchSignInMethodsForEmail().
The usual flow for this is that you first ask the user to enter their email address, then call fetchSignInMethodsForEmail, and then move them to a screen that either asks for the rest of their registration details (if they're new), or show them the provider(s) with which they're signed up already.
When the user trying to create an user with same email address, the task response will be "Response: The email address is already in use by another account."
mFirebaseAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//User registered successfully
}else{
Log.i("Response","Failed to create user:"+task.getException().getMessage());
}
}
});
First of all, you need to make sure you have that restriction enabled in Firebase console (Account and email address settings). Take a look at #Srinivasan's answer.
Then, do this in your java code:
firebaseAuthenticator.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
if (task.getException() instanceof FirebaseAuthUserCollisionException) {
Toast.makeText(SignUpActivity.this, "User with this email already exist.", Toast.LENGTH_SHORT).show();
}
} else {
sendVerificationEmail();
startActivity(new Intent(SignUpActivity.this, DetailsCaptureActivity.class));
}
// ...
}
});
This is where the trick happens:
if (task.getException() instanceof FirebaseAuthUserCollisionException) {
Toast.makeText(SignUpActivity.this,
"User with this email already exist.", Toast.LENGTH_SHORT).show();
Several exceptions can be thrown when registering a user with email and password, but the one we are interested in is the FirebaseAuthUserCollisionException. As the name implies, this exception is thrown if the email already exists. If the exception thrown is an instance of this class, let the user know.
As a practice of #Frank's answer here is the code of using fetchProvidersForEmail()
private boolean checkAccountEmailExistInFirebase(String email) {
FirebaseAuth mAuth = FirebaseAuth.getInstance();
final boolean[] b = new boolean[1];
mAuth.fetchProvidersForEmail(email).addOnCompleteListener(new OnCompleteListener<ProviderQueryResult>() {
#Override
public void onComplete(#NonNull Task<ProviderQueryResult> task) {
b[0] = !task.getResult().getProviders().isEmpty();
}
});
return b[0];
}
I was looking into this kind of condition where we can detect if user exists or not and perform registration and login. fetchProvidersForEmail is best option right now. I have found this tutorial. Hope it helps you too!
See : Manage Users
UserRecord userRecord = FirebaseAuth.getInstance().getUserByEmail(email);
System.out.println("Successfully fetched user data: " + userRecord.getEmail());
This method returns a UserRecord object for the user corresponding to the email provided.
If the provided email does not belong to an existing user or the user cannot be fetched for any other reason, the Admin SDK throws an error. For a full list of error codes, including descriptions and resolution steps, see Admin Authentication API Errors.
private ProgressDialog progressDialog;
progressDialog.setMessage("Registering, please Wait...");
progressDialog.show();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//checking if success
if (task.isSuccessful()) {
//Registration was successfull:
Toast.makeText(RegistrationActivity.this, "Successfully registered!", Toast.LENGTH_LONG).show();
} else {
//Registration failed:
//task.getException().getMessage() makes the magic
Toast.makeText(RegistrationActivity.this, "Registration failed! " + "\n" + task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
Add below code to MainActivity.java file.When user attempt to register with the same email address a message "The email address is already used by another account" will pop up as a Toast
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "Sign up successfull", Toast.LENGTH_SHORT).show();
}
}
});
You do not have to do anything because the backend of Firebase will do the job.
Unless you are referring to reauthenticating of the app.
Take a scenario for an example, w
I am creating an android app that registers a user to firebase Authentication. So as you can see below this is the program i made to give you a hint on what i am referring . . .
public void createAccount(final String email, final String password, final String firstname, final String lastname)
{
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
UserInformation UInfo = new UserInformation(user.getUid(), user.getEmail(), password, firstname, lastname);
newRef = database.getReference("Users");
newRef.child(user.getUid()).setValue(UInfo);
//newRef.child(user.getUid()).child("id").setValue(user.getUid());
Toast.makeText(Signup.this, "User registered: " + user.getEmail(), Toast.LENGTH_LONG).show();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(Signup.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
after register succeeds all other devices also gets affected as well, in terms of, all the other devices prompts as if they've just logged in again.
my problem is, why does it do that? why does all other devices gets affected as if they've just logged in again. what's causing the issue?
also, this is my database rules.
{
"rules": {
".read": true,
".write": true
}
}
I am pretty new to Firebase and have a question.
I'm looking to link my new authenticated user to a database that I have working.
I have class named addChild which contains an editText for add children's name, and need this to be linked to the authenticated user on a database. So when that user logs in, they can see their children's names that they have inputted.
Does anybody know how I could do this? I have set up the real-time database connection Im just not sure where to go from here.
Thanks
This is how I created user.
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(CreateUserAccount.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(CreateUserAccount.this, "User Account Created" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Toast.makeText(CreateUserAccount.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(CreateUserAccount.this, LandingPage.class));
finish();
}
}
});
After you authenticate a user using Firebase Authentication, then also you can send his uid to the database:
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
String useruid=user.getUid();
then in the database you would have this:
Users
useruid
name: userx
email: userx#gmail.com
String name = editText.getText().toString();
String email = editTxt.getText().toString();
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Users").child(useruid);
ref.child("name").setValue(name);
ref.child("email").setValue(email);
Edit:
} else {
FirebaseUser user= task.getResult().getUser();
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Users").child(user.getUid());
ref.child("name").setValue(name);
ref.child("email").setValue(email);
startActivity(new Intent(CreateUserAccount.this, LandingPage.class));
finish();
}
to add the children in the other activity:
First retrieve the names from an edittext
then add them like this:
Children
useruid <--- the id that is in the usernode above
childname: john
useruid
childname: james bond
This Question was created as my previous question contained 2 question instead of narrowing it down to 1
Aim
Users will be able to store new data without overwriting their previously submitted data
Description
Currently, the User's Incident Report data within the Incident Report node will be overwritten when the User enters a new Report.
The Data from the old Incident Report sent by the user should be kept along with the new data.
This way the authorities will be able to view the previous reports and also the new report data.
Problem
Everytime a the currently signed in user saves a "Report", the New report data will overwrite the Old report data
Codes for Saving Data
private void submitReport(final String userReportDate,final String userReportTime,
final String userReportLocation,final String userReportDescription) {
jReportCurrentUserID = FirebaseAuth.getInstance().getCurrentUser();
final String reportUserID = jReportCurrentUserID.getUid();
jReportByUserDatabase = FirebaseDatabase.getInstance().getReference().child("Incident Reports").child(reportUserID);
HashMap<String, String> incidentReportUser = new HashMap<>();
incidentReportUser.put("date", userReportDate);
incidentReportUser.put("time", userReportTime);
incidentReportUser.put("location", userReportLocation);
incidentReportUser.put("description", userReportDescription);
jReportByUserDatabase.setValue(incidentReportUser).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
jReportLoad.dismiss();
Toast.makeText(getActivity(), "Report was Sent", Toast.LENGTH_SHORT).show();
jReportDatePick.setText("");
jReportTimeEnt.setText("");
jReportLocationEnt.setText("");
jReportDescriptionEnt.setText("");
}else{
jReportLoad.dismiss();
Toast.makeText(getActivity(), "Report failed to be sent", Toast.LENGTH_SHORT).show();
}
}
});
}
jReportByUserDatabase.push().setValue(incidentReportUser)
Write it this way (push() adds values instead of overriding).
See push documentation
Note that your all your reports will now be stored one level down under a unique key created by .push()
private void submitReport(final String userReportDate,final String userReportTime,
final String userReportLocation,final String userReportDescription) {
jReportCurrentUserID = FirebaseAuth.getInstance().getCurrentUser();
final String reportUserID = jReportCurrentUserID.getUid();
jReportByUserDatabase = FirebaseDatabase.getInstance().getReference().child("Incident Reports").child(reportUserID).push();
DatabaseReference newReport = jReportByUserDatabase.push();
HashMap<String, String> incidentReportUser = new HashMap<>();
incidentReportUser.put("date", userReportDate);
incidentReportUser.put("time", userReportTime);
incidentReportUser.put("location", userReportLocation);
incidentReportUser.put("description", userReportDescription);
newReport.setValue(incidentReportUser).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
jReportLoad.dismiss();
Toast.makeText(getActivity(), "Report was Sent", Toast.LENGTH_SHORT).show();
jReportDatePick.setText("");
jReportTimeEnt.setText("");
jReportLocationEnt.setText("");
jReportDescriptionEnt.setText("");
}else{
jReportLoad.dismiss();
Toast.makeText(getActivity(), "Report failed to be sent", Toast.LENGTH_SHORT).show();
}
}
});
}