jobin
jobin

Reputation: 1517

Android app crashes on firebase phone authentication

I am using firebase for phone number authentication.When I used my phone number, it automatically verifies it.But when I use another phone number I get classCastException.It says "getGoogleApiForMethod() returned Gms".There is a similar problem in stackoverflow Link.The answer was to downgrade firebase or google play services in phone or emulator.I have included gradle as well below.Please check it

Exception:

W/BiChannelGoogleApi: [FirebaseAuth: ] getGoogleApiForMethod() returned Gms: com.google.firebase.auth.api.internal.zzal@c2c24f7
05-11 15:00:05.597 29282-29282/ W/System.err: java.lang.ClassCastException: Otp.OtpCodeFrag cannot be cast to java.util.concurrent.Executor
05-11 15:00:05.607 29282-29282/ W/System.err:     at Otp.OtpCodeFrag.signInWithPhoneAuthCredential(OtpCodeFrag.java:402)
        at Otp.OtpCodeFrag.access$200(OtpCodeFrag.java:39)
        Otp.OtpCodeFrag$2.onClick(OtpCodeFrag.java:222)
        at android.view.View.performClick(View.java:5716)
        at android.widget.TextView.performClick(TextView.java:10926)
        at android.view.View$PerformClick.run(View.java:22596)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:7325)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

OTPFrag.java:

        onVerificationStateChangedCallbacks=new PhoneAuthProvider.OnVerificationStateChangedCallbacks()
                    {
                        @Override
                        public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential)
                        {
                            phoneauthCredential = phoneAuthCredential;
                            automatic_verification = true;

                            Toast.makeText(getContext(), "Verification Completed", Toast.LENGTH_SHORT).show();

                        }
                        @Override
                        public void onVerificationFailed(FirebaseException e) {
                            Toast.makeText(getContext(),"Verification Failed",Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }

                        @Override
                        public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken)
                        {
                            super.onCodeSent(s, forceResendingToken);
                            Toast.makeText(getContext(),"CodeSent",Toast.LENGTH_SHORT).show();
                            verificationid=s;
                            codesent=true;
                            token=forceResendingToken.toString();
                            Log.e("Token",token);
                            Log.e("ID",s);
        //                           smscode=phoneauthCredential.getSmsCode();
                        }
                        };

                    PhoneAuthProvider.getInstance().verifyPhoneNumber(
                        phonenumber,        // Phone number to verify
                        4,                 // Timeout duration
                        TimeUnit.SECONDS,   // Unit of timeout
                        getActivity(),               // Activity (for callback binding)
                        onVerificationStateChangedCallbacks);

    otpCodeLytBinding.verifyOtp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {

                code1=otpCodeLytBinding.cd1.getText().toString();
                code2=otpCodeLytBinding.cd2.getText().toString();
                code3=otpCodeLytBinding.cd3.getText().toString();
                code4=otpCodeLytBinding.cd4.getText().toString();
                code5=otpCodeLytBinding.cd5.getText().toString();
                code6=otpCodeLytBinding.cd6.getText().toString();
                   if (code1!=null&&!code1.equals("")&&code2!=null&&
                   !code2.equals("")&&code3!=null&&!code3.equals("")
                   &&code4!=null&&!code4.equals("")&&code5!=null
                   &&!code5.equals("")&&code6!=null&&!code6.equals(""))
               {
                   completecode=code1+code2+code3+code4+code5+code6;
                   Log.e("cm",completecode);
                   try {
                       if (verificationid!=null&&completecode!=null){

                           PhoneAuthCredential credential = PhoneAuthProvider.
                               getCredential(verificationid, completecode);
                           signInWithPhoneAuthCredential(credential);
                       }
                       else {
                           Toast.makeText(getContext(),"Something null",Toast.LENGTH_SHORT).show();
                       }
                   }
                   catch (Exception e)
                   {
                       e.printStackTrace();
                   }

               }
               else {
                       Toast.makeText(getContext(),"Please enter otp",Toast.LENGTH_SHORT).show();
                   }
            }
        });
     private void signInWithPhoneAuthCredential(PhoneAuthCredential credential)
        {
            Log.e("SigningIn","Started");
            mAuth.signInWithCredential(credential)
                    .addOnCompleteListener((Executor) 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, "signInWithCredential:success");
    //
    //                            FirebaseUser user = task.getResult().getUser();
                                                          }
 else {
                                // Sign in failed, display a message and update the UI
                                Log.w(TAG, "signInWithCredential:failure", task.getException());
                                if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                                    // The verification code entered was invalid
                                }
                            }
                        }
                    });
        }

build.gradle(app):

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.root5solutions.loc8official"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dataBinding {
        enabled = true
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    implementation 'com.balysv:material-ripple:1.0.2'

//    implementation 'com.appolica:flubber:1.0.1'
    implementation 'com.google.firebase:firebase-core:15.0.2'
    implementation 'com.google.firebase:firebase-auth:15.1.0'
    testImplementation 'junit:junit:4.12'
//    androidTestImplementation 'com.android.support.test:runner:1.0.2'
//    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
apply plugin: 'com.google.gms.google-services'

build.gradle(Project):

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.1'
        classpath 'com.google.gms:google-services:3.2.0'



        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven {
            url "https://maven.google.com" // Google's Maven repository
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Upvotes: 0

Views: 2034

Answers (3)

Sachidanand Navik
Sachidanand Navik

Reputation: 1

I am too late but it worked for me, Use

mAuth.signInWithCredential(credential)
            .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        FirebaseUser user = Objects.requireNonNull(task.getResult()).getUser();
                        // handel success
                    } else if (task.isCanceled()){
                       // handel error
                    }
                }
            });

Instead of using

 mAuth.signInWithCredential(credential)
                .addOnCompleteListener((Executor) 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, "signInWithCredential:success");
//
//                            FirebaseUser user = task.getResult().getUser();
                                                      } else {
                            // Sign in failed, display a message and update the UI
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                                // The verification code entered was invalid
                            }
                        }
                    }
                });

I think that (Executer)this context is creating the problem try removing that, not just Executer but any context generates error, I don't know why..

Upvotes: 0

Duna
Duna

Reputation: 1612

In case you don't need a reference to an Activity then replace (Executor) this with the following code:

new Executor() {
    @Override
    public void execute(Runnable command) {}
}

Upvotes: 1

Doug Stevenson
Doug Stevenson

Reputation: 317322

I don't know what you're trying to do with this line:

.addOnCompleteListener((Executor) this, new OnCompleteListener<AuthResult>() {

Casting this to Executor doesn't seem to make sense. What you want instead of this is a reference to the current Activity. Try getActivity() instead to get this reference.

Upvotes: 2

Related Questions