Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check "user email already exists" in firebase using Android Studio

I'm trying to change my code. But, its failed. My output still the same. Which is, if the user put an email that is already exist or not already exist. The validation "This email has been registered." still came out. Why? Can someone whats wrong with my coding?

Here are my method:-

public boolean isCheckEmail(final String email)
{
    mAuth.fetchProvidersForEmail(email).addOnCompleteListener(new OnCompleteListener<ProviderQueryResult>()
    {
        @Override
        public void onComplete(@NonNull Task<ProviderQueryResult> task)
        {
            boolean check = !task.getResult().getProviders().isEmpty();

            if(check)
            {
                Toast.makeText(Signup.this, "This email has been registered.", Toast.LENGTH_SHORT).show();
            }

            else
            {
                Toast.makeText(Signup.this, "This email has been registered.", Toast.LENGTH_SHORT).show();
            }
        }
    });
    return true;
}

While this half coding, I'm trying to call back the method isCheckEmail:-

 private void RegisterAccount(String firstname, String lastname, String email, String password, String confirmpass)
{
    if (TextUtils.isEmpty(email))
    {
        Toast.makeText(Signup.this, "Enter your email address.", Toast.LENGTH_SHORT).show();
    }

    else if (!isValidEmail(email)) {
        Toast.makeText(Signup.this,"Please enter your valid email address.",Toast.LENGTH_SHORT).show();
    }

    else if (!isCheckEmail(email))
    {
        Toast.makeText(Signup.this, "This email has been registered.", Toast.LENGTH_SHORT).show();
    }
like image 825
Daisy Avatar asked Aug 05 '18 12:08

Daisy


People also ask

How to authenticate users using email in Firebase?

Now we have to enable the authentication function in the Firebase project. After clicking on the enable button in the sign-in-method option choose the method which you want to use for Authentication. Let’s explore how to Authenticate users using email addresses.

How do I use Firebase assistant in Android Studio?

You can now open and use the Assistant window in Android Studio by following these steps: Click Tools > Firebase to open the Assistant window. Click to expand one of the listed features (for example, Analytics), then click the Get Started tutorial to connect to Firebase and add the necessary code to your app.

How to create and register a project on Firebase?

To register the project on Firebase follows the steps: Click on add project, after clicking you will redirect to create project tab. On the create project tab give the project name, and click on the continue button. Follow the steps and click on create the project.

What is the use of Firebase?

It provides services that a web application or mobile application might require. Firebase provides email and password authentication without any overhead of building backend for user authentication. Steps for firebase user authentication are:


4 Answers

this method works to check either email existed or not

 void checkEmailExistsOrNot(){
    firebaseauth.fetchSignInMethodsForEmail(email.getText().toString()).addOnCompleteListener(new OnCompleteListener<SignInMethodQueryResult>() {
        @Override
        public void onComplete(@NonNull Task<SignInMethodQueryResult> task) {
            Log.d(TAG,""+task.getResult().getSignInMethods().size());
            if (task.getResult().getSignInMethods().size() == 0){
                // email not existed
            }else {
                // email existed
            }

        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            e.printStackTrace();
        }
    });
}
like image 108
saigopi.me Avatar answered Oct 26 '22 20:10

saigopi.me


fetchProvidersForEmail is an async call so you have to make use of its return value with the callback.

return true on the main thread will not work.

Here is the solution :

First Create an interface with the method (success)

public interface OnEmailCheckListener(){
 void onSuccess(boolean isRegistered);
} 

Your checkEmail Method should be like this:

public void isCheckEmail(final String email,final OnEmailCheckListener listener){
mAuth.fetchProvidersForEmail(email).addOnCompleteListener(new OnCompleteListener<ProviderQueryResult>()
{
    @Override
    public void onComplete(@NonNull Task<ProviderQueryResult> task)
    {
        boolean check = !task.getResult().getProviders().isEmpty();
        
        listener.onSuccess(check);
     
    }
});

}

Finally call your isCheckEmail like this :

isCheckEmail("[email protected]",new OnEmailCheckListener(){
   @Override
   void onSuccess(boolean isRegistered){
    
     if(isRegistered){
           //The email was registered before
    } else {
           //The email not registered before
    }

   }
});

Hope this helps you.

like image 36
Mohamed Yehia Avatar answered Oct 26 '22 18:10

Mohamed Yehia


Firebase automatically tells you if an email that you want to create an account with already exists. When creating an account you should check if the task was succesfull and under

if(task.isSuccessful()) {} // you have this code in your last bit of code
else{}                     // you have this in your code already

(

you currently have the code

Toast.makeText(getApplicationContext(), "registration not performed", Toast.LENGTH_SHORT).show();

( it is pretty much the last line in the code you provided) but you should replace it with:

try {
    throw task.getException();
} catch(FirebaseAuthUserCollisionException e) {
    // email already in use
Toast.makeText(getApplicationContext(), "Email already taken!", Toast.LENGTH_SHORT).show();
}

So you do not need to check if an email exists yourself because Firebase will automatically throw an exception and then you can for example display a toast.

like image 25
Kleysley Avatar answered Oct 26 '22 19:10

Kleysley


Kotlin version of Sai Gopi Me's answer

fun checkEmailExistsOrNot() {

        FirebaseAuth
        .getInstance()
        .fetchSignInMethodsForEmail(binding.etEmail.value())
        .addOnCompleteListener { task ->

            Log.d(TAG, "" + task.result?.signInMethods?.size)

            if (task.result?.signInMethods?.size === 0) {
                // email not existed
                Log.d(TAG, "email  not existed")
            } else {
                // email existed
                Log.d(TAG, "checkEmailExistsOrNot: ")

            }
        }.addOnFailureListener {
                e -> e.printStackTrace()
        }

}
like image 39
Ahmad Salman Avatar answered Oct 26 '22 19:10

Ahmad Salman