Firebase onCompleteListener code being skipped - android

I'm making an app where a signed-in user can create another account, so in this code, another user is already signed in, check the toasts to see the order the code is being executed.
btnCreateCompany.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseAuth.createUserWithEmailAndPassword(txtCompanyEmail.getText().toString(), txtCompanyPassword.getText().toString())
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(getApplicationContext(), "THIS TOAST IS COMING UP SECOND", Toast.LENGTH_SHORT).show();
if (!task.isSuccessful())
Toast.makeText(getApplicationContext(), "SOMETHING WENT WRONG", Toast.LENGTH_SHORT).show();
else {
Toast.makeText(getApplicationContext(), "THIS TOAST IS COMING UP THIRD", Toast.LENGTH_SHORT).show();
FirebaseUser userCreated = task.getResult().getUser();
userCreated.sendEmailVerification();
userID = userCreated.getUid();//userID is a private field
}
}
}); //After reaching the third toast the code adter onComplete doesn't execute anymore
if (userID == null)
Toast.makeText(getApplicationContext(), "THIS TOAST IS COMING UP FIRST", Toast.LENGTH_SHORT).show();
else {
companyRef = db.collection("companyData").document(userID); (...) }

Creating the user is an asynchronous operation. Any code that needs access to the newly created user, needs to be inside the onComplete method or be called from there.
So something like:
btnCreateCompany.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseAuth
.createUserWithEmailAndPassword(txtCompanyEmail.getText().toString(), txtCompanyPassword.getText().toString())
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(getApplicationContext(), "THIS TOAST IS COMING UP SECOND", Toast.LENGTH_SHORT).show();
if (!task.isSuccessful()) }
Toast.makeText(getApplicationContext(), "SOMETHING WENT WRONG", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(), "THIS TOAST IS COMING UP THIRD", Toast.LENGTH_SHORT).show();
FirebaseUser userCreated = task.getResult().getUser();
userCreated.sendEmailVerification();
userID = userCreated.getUid();//userID is a private field
}
if (userID == null) {
Toast.makeText(getApplicationContext(), "THIS TOAST IS COMING UP FIRST", Toast.LENGTH_SHORT).show();
}
else {
companyRef = db.collection("companyData").document(userID); (...) }
}
});

The call to:
task.getResult().getUser();
may not work. Try to log firebaseauth.getCurrentUser() and task.getResult().getUser() inside task.isSuccessful() to better understand what's going on.
I can suggest different approaches to this if you fail to debug:
1) Set up the Firebase Admin SDK to create a new user from your app:
https://firebase.google.com/docs/auth/admin/manage-users#create_a_user
OR
2) Set up a cloud function using Node.Js like this one:
https://stackoverflow.com/a/43808854/13473423
and then call your cloud functions to create and new user from your app. Handling it on the server side means it won't interfere with the "Current" FirebaseUser and thus will work!
Check this answer on how to call cloud functions locally:
https://firebase.google.com/docs/auth/admin/manage-users#create_a_user

Maybe this works. So try to replace this line
FirebaseUser userCreated = task.getResult().getUser();
with this:
FirebaseUser userCreated = firebaseauth.getCurrentUser();

Related

Firebase User Verification Email

I am using Firebase as the Backend for an Mobile Android Application. When a User registers, I would like to have a verification email sent to that user.
When the User Clicks the "SignUp" button, the following logic is run through: First of all a number of variables are set from the filled in boxes. Then a few checks are performed on validity of the filled in parameters. If the checks are passed, a user is created in the Database. This is all functioning..
Then I would like to send a verification email to the user to check if the email is valid. I have also put this in the onClick method of the Button but this is not functioning yet.
I do not receive the verification email.
What is the reason behind this and the fix?
My onCreate Method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_sign_up_page);
setFontType();
screen = (EditText)findViewById(R.id.SchermNaam);
mail = (EditText)findViewById(R.id.EmailAdres);
knop = (Button)findViewById(R.id.SignUp_Button_SignUp);
firebaseAuth = FirebaseAuth.getInstance();
}
The onClick method for the "SignUp" Button:
public void onClickSignUpPage(View view){
String schermnaam = screen.getText().toString().trim();
String emailadres = mail.getText().toString().trim();
String paswoord = pass.getText().toString().trim();
if(TextUtils.isEmpty(schermnaam)){
Toast.makeText(this,"Schermnaam invullen", Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(emailadres)){
Toast.makeText(this,"Email invullen",Toast.LENGTH_SHORT).show();
return;
}
if(!schermnaam_ok(schermnaam)){
Toast.makeText(this,"schermnaam minstens 5 en maximum 15 tekens", Toast.LENGTH_SHORT).show();
return;
}
if(!paswoord_ok(paswoord)){
Toast.makeText(this,"paswoord tussen 6-12 karakters en minstens 1 cijfer", Toast.LENGTH_SHORT).show();
return;
}
firebaseAuth.createUserWithEmailAndPassword(emailadres.trim(),paswoord)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(SignUpPage.this, "Nieuwe Speler Geregistreerd", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SignUpPage.this, SignInPage.class);
startActivity(intent);
}
else {
FirebaseAuthException e = (FirebaseAuthException) task.getException();
Toast.makeText(SignUpPage.this,"Fout in de SignUp"+e.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("LoginActivity", "Failed Registration", e);
return;
}
}
});
FirebaseUser user = firebaseAuth.getCurrentUser();
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Email sent.");
}
}
});
}
Changed it up to a sequential procedure, as suggested by the post quoted by #cramopy. Thank you for this!
Now you first need to "Sign Up" as a user, and then verify in another step, through another button. Then I receive the confirmation email.
Here my code for the onClick method for the 2 Buttons.. From a UX point of view, need to look at how to position the buttons. This is a functional viewpoint.
public void onClickSignUpPage(View view){
String schermnaam = screen.getText().toString().trim();
String emailadres = mail.getText().toString().trim();
String paswoord = pass.getText().toString().trim();
if(TextUtils.isEmpty(schermnaam)){
Toast.makeText(this,"Schermnaam invullen", Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(emailadres)){
Toast.makeText(this,"Email invullen",Toast.LENGTH_SHORT).show();
return;
}
if(!schermnaam_ok(schermnaam)){
Toast.makeText(this,"schermnaam minstens 5 en maximum 15 tekens", Toast.LENGTH_SHORT).show();
return;
}
if(!paswoord_ok(paswoord)){
Toast.makeText(this,"paswoord tussen 6-12 karakters en minstens 1 cijfer", Toast.LENGTH_SHORT).show();
return;
}
firebaseAuth.createUserWithEmailAndPassword(emailadres.trim(),paswoord)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(SignUpPage.this, "Nieuwe Speler Geregistreerd", Toast.LENGTH_SHORT).show();
}
else {
FirebaseAuthException e = (FirebaseAuthException) task.getException();
Toast.makeText(SignUpPage.this,"Fout in de SignUp"+e.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("LoginActivity", "Failed Registration", e);
return;
}
}
});
AddDataFireBase();
}
public void onClickVerify(View view){
FirebaseUser user = firebaseAuth.getCurrentUser();
assert user != null;
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Email sent.");
}
else {
Log.e(TAG, "sendEmailVerification", task.getException());
Toast.makeText(SignUpPage.this,
"Failed to send verification email.",
Toast.LENGTH_SHORT).show();
}}
});
Intent intent = new Intent(SignUpPage.this, SignInPage.class);
startActivity(intent);
}
Your code should work. But I suggest you to follow the next steps to verify the email:
Create account
Check if creation was successful
Check if the email is verified with user.isEmailVerified()
Reload your user to update the instance with user.reload(). You should do this because some methods on Firebase ask you to reload or reauthenticate the user before realize some operations. Reload in this case will update the cache and data of your user.
Send the email using sendEmailVerification()
Something like:
authInstance.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener {
if (it.isSuccessful) {
//Create accountData in the database
if (it.result!!.user.isEmailVerified) {
it.result!!.user.reload()
.addOnCompleteListener {
if (it.isSuccessful) {
authInstance.currentUser!!.sendEmailVerification()
.addOnCompleteListener {
Log.i("TAG", "Yay! verificationSent")
}
} else {
//Manage error
}
}
}
} else {
//Manage error
}
}
Also, you should know that sometimes the email verification takes some time in Debug environments(at least from my experience I have saw delays of 1-3 minutes, but never on release versions).
Finally, before call user.verify() you should need to call again user.reload() to update the data of your user in the Firebase Cache, if not, even if you have click on Verify my email on the email sent to your account, the FirebaseAuthor.currentUser().isEmailVerified() will continue returning you false.

Firebase Send Verification Email doesn't work

I was wondering if anybody else has the same problem, I'm working on a project using Firebase Email and Password for login, everything works fine except Verification Email, here's the code down there does anybody else has this problem? is it belong to Google? or it's something that I'm doing it wrong?
because the signUp method works fine and the user will be created after user press the Register button, but sendVerificationEmail method never been called
this is the signUp method which includes sendVerificationEmail method:
if (checkSignUpFormFields()) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(LaunchActivity.this, "Your account successfully created", Toast.LENGTH_SHORT).show();
sendVerificationEmail();
FirebaseAuth.getInstance().signOut();
} else {
Toast.makeText(LaunchActivity.this, "something went wrong, Check your information",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
}
});
}
and this is the method for sending verification method:
private void sendVerificationEmail(){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null){
user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(LaunchActivity.this, "Verification Email has been sent.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LaunchActivity.this, "Something went wrong!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
There's some issue with Firebase itself, I received an Email for a registration I've made about an hour ago, it's just taking so long more than an hour or so, and must be Googles issue.

Verified user with Firebase

I want to create a login where the user only has to put his/her mail address and verify it via email. Using firebase I have this code so far:
When the user clicks the button to login after putting the mail in the field. I try to create a new account (password is random as I don't need it). If it doesn't exists I send a verification mail. If the account exists I check with checkIfVerifiedUser if the user verified the account by clicking the mail or not.
firebaseAuth.createUserWithEmailAndPassword(email, Math.random() + "").addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = firebaseAuth.getCurrentUser();
user.sendEmailVerification().addOnCompleteListener((Activity) context, new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Toast.makeText(context, "we sent a mail, please verify", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "error", Toast.LENGTH_LONG).show();
}
}
});
checkIfVerifiedUser(email);
} else {
progressDialog.dismiss();
try {
throw task.getException();
} catch (FirebaseAuthUserCollisionException e) {
// In case the account already exists
checkIfVerifiedUser(email);
} catch (Exception e) {
Toast.makeText(context, R.string.error_auth, Toast.LENGTH_SHORT).show();
}
}
} });
Here is the method I call:
private void checkIfVerifiedUser(String email){
final FirebaseUser user = firebaseAuth.getCurrentUser();
Intent intent = new Intent(context, HomeActivity.class);
if(user != null){
user.reload();
// If the user is created, we check if the account is verified
if(user.isEmailVerified()) {
intent.putExtra(IntentEnum.ALREADYREGISTERED.getCode(), true);
}else{
intent.putExtra(IntentEnum.ALREADYREGISTERED.getCode(), false);
}
}else{
intent.putExtra(IntentEnum.ALREADYREGISTERED.getCode(), false);
}
---rest of code---
}
The problem is that I either get firebaseAuth.getCurrentUser() == null or user.isEmailVerified() always false (even if I click the link in the email I get sent).
Could anyone help me with this?
Thanks!
To solve this, you need to call checkIfVerifiedUser() method inside onComplete() method and inside the if statement.
Hope it helps.

createUserWithEmailAndPassword issue

I am testing the createUserWithEmailAndPassword feature but It does not seem to be working.
private void createUserAccount() {
String userEmail, userPassword;
userEmail = emailRegisterEditText.getText().toString();
userPassword = passwordRegisterEditText.getText().toString();
if (!TextUtils.isEmpty(userEmail) && !TextUtils.isEmpty(userPassword)) {
mAuth.createUserWithEmailAndPassword(userEmail, userPassword)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(RegisterUserActivity.this, "Account created successfully", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
startActivity(new Intent(RegisterUserActivity.this, InstagramHomeActivity.class));
} else {
Toast.makeText(RegisterUserActivity.this, "Failed to create account", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
}
});
}
}
I have googled the issue and others have similar problems but they have a toast appear for failure. Neither a toast appears for success or failure and the ProgressDialog does not disappear for me. I am thinking that maybe it's processing or there is an error on the firebase side? Any help is appreciated. Thanks

Having created a new account, I automatically enter it

Having created a new account, I automatically enter it.
How do I prevent my account from being created?
firebaseAuth.createUserWithEmailAndPassword(em, pass).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Пользователь добавлен", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
} else {
Toast.makeText(getApplicationContext(), "Пользователь не добавлен", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
May be need workes whis admin sdk?
May be who worked with admin sdk firebase android?
Are there any examples or lessons on working with admin sdk?
For I do not understand how to work with this.
The way I understand Firebase to work is that if the task is successful then Firebase actually actually signs in the user.
firebaseAuth.createUserWithEmailAndPassword(em, pass).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseAuth.getInstance().getCurrentUser();
//Ther will be a current user at this point. This is the way Firebase just works.
progressDialog.dismiss();
} else {
Toast.makeText(getApplicationContext(), "Пользователь не добавлен", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
So you can actually get the user after the task is successful because the user is automatically set if the task is successful. If you would not like there to be any user when the task is successful. You can call
FirebaseAuth.getInstance().signOut();
This will sign out the user and when you call
Firebase.getInstance().getCurrentUser()
This will return nothing, that way there will be no user in your system.
firebaseAuth.createUserWithEmailAndPassword(em, pass).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseAuth.getInstance().getCurrentUser();
//Ther will be a current user at this point. This is the way Firebase just works.
FirebaseAuth.getInstance().signOut();// sign out the user
Firebase.geInstance().getCurrentUser(); // this will now be null
progressDialog.dismiss();
} else {
Toast.makeText(getApplicationContext(), "Пользователь не добавлен", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});

Categories

Resources