Firebase link email to phone: Cannot create PhoneAuthCredential without verificationProof - java

So I had my Phone Verify working since I updated my Firebase last week. Since then I'm facing the problem that in my linking process where I'm connecting the users email to the phone number doesn't work anymore:
java.lang.IllegalArgumentException: Cannot create PhoneAuthCredential without either verificationProof, sessionInfo, ortemprary proof.
I've seen some users with the same problem but nobody with a solution.
I tried to rewrite the whole Code but the problem is still there. Has Firebase changed something in the linking process?
As I have seen in the Firebase Linking Documentation, the section about Phone Number linking was removed.
Is something wrong with my code or is it a problem with firebase?
Firebase Versions I'm using:
implementation 'com.google.firebase:firebase-core:16.0.8'
implementation 'com.google.firebase:firebase-messaging:17.6.0'
implementation 'com.google.firebase:firebase-perf:16.2.5'
implementation 'com.android.support:support-compat:28.0.0'
implementation 'com.google.firebase:firebase-auth:16.2.1'
implementation 'com.google.firebase:firebase-storage:16.1.0'
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_phone_verify);
Log.e("PhoneVerify","Start");
mAuth = FirebaseAuth.getInstance();
editTextCode = findViewById(R.id.editTextCode);
editTextPhone = findViewById(R.id.editTextPhone);
Bundle extras = getIntent().getExtras();
if (extras !=null) {
final String phone = extras.getString("phone");
Log.e("Phone(Extras):",phone);
editTextPhone.setText(phone);
sendVerificationCode(phone);
}
findViewById(R.id.buttonGetVerificationCode).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String phone = editTextPhone.getText().toString().trim();
if (phone.isEmpty() || phone.length() < 10) {
editTextPhone.setError("Phone number error");
editTextPhone.requestFocus();
return;
}
sendVerificationCode(phone);
}
});
findViewById(R.id.buttonSignIn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
verifyVerificationCode(editTextCode.getText().toString());
}
});
}
private void sendVerificationCode(String phonenumber) {
String phone = "+14" + phonenumber;
Log.e("sendVerificationCode",phone);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phone, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
}
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
//Getting the code sent by SMS
final String code = phoneAuthCredential.getSmsCode();
if (code != null) {
editTextCode.setText(code);
//verifying the code
verifyVerificationCode(code);
Log.e("onVerificationCompleted",code);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Log.e("onVerificationFailed", String.valueOf(e));
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
Log.e("onCodeSent", "Code Sent");
codeSent = s;
PhoneAuthProvider.ForceResendingToken mResendToken = forceResendingToken;
}
};
private void verifyVerificationCode(String code) {
//creating the credential
try {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codeSent, code);
linkWithCredential(credential,code);
} catch (Exception e) {
Log.e("Exception", String.valueOf(e));
}
Log.e("VerifyCode CHECKP",code);
//signing the user
}
private void linkWithCredential(final AuthCredential credential, final String code) {
mAuth.getCurrentUser().linkWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.e("Linking Phone to Email","Successfull");
try {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codeSent, code);
signInWithPhoneAuthCredential(credential);
} catch (Exception e) {
Log.e("Exception", String.valueOf(e));
}
}
});
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(PhoneVerify.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//verification successful we will start the profile activity
Log.e("FINAL LINK","DONE");
} else {
//verification unsuccessful.. display an error message
String message = "Somthing is wrong, we will fix it soon...";
});
}
}

Here how to use Firebase Phone Authentication from Firebase docs
https://firebase.google.com/docs/auth/android/phone-auth
and linking Authentication provider
https://firebase.google.com/docs/auth/android/account-linking
//please notice, mCallback.onVerificationCompleted will automatically called
//if verification code already send to your phone
//(Maybe not called in some case)
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
linkPhoneAuthToCurrentUser(credential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
//show error
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
//save id and token in case you need to resend verification code
}
};
//call this to send verification code
//parameter include country code
private void sendVerificationCode(String phonenumber) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phonenumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
}
//link auth with credential
private void linkPhoneAuthToCurrentUser(PhoneAuthCredential credential) {
FirebaseAuth.getInstance().getCurrentUser().linkWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//link auth success update ui
} else {
//link auth failed update ui
}
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_phone_verify);
//init view
//get phone number
String phoneNumb = "Add Your Phone Number Here"
sendVerificationCode(phoneNumb)
//if mCallback not called,
//use this button to sign in with manual input verification code
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//get verification id from mCallback.onCodeSent
//get verificationCode manually from edittext
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, verificationCode);
linkPhoneAuthToCurrentUser(credential);
}
});
}
PS : you need to re-authenticate your email authentication before link phone number authentication. Follow this link to re-authenticate https://firebase.google.com/docs/auth/android/manage-users#re-authenticate_a_user

onVerificationCompleted is called when firebase automatically verifies the phone number by detecting the sms code sent to the phone.
I think you should reformat your code to either use only the credential here, or the one you generate manually by combination of the code entered by the user and verificationId; and not both.
Also no need to sign in again with phone credential, you already signed in
I mean you should have something like this instead,
private void linkWithCredential(final PhoneAuthCredential credential) {
mAuth.getCurrentUser().linkWithCredential(credential).addOnComplete.......{
onComplete(....) {
.....
//signInWithPhoneCredential(credential);
// You Already signed in. No need. Just update the ui with the user info
}
https://firebase.google.com/docs/auth/android/account-linking

Related

How to solve this this error. com.google.android.gms.tasks.task executors$zza cannot be cast to android.app.activity. I am new at Java & Android app

I want to verify user through phone number verification OTP code, now I am unable to fix this issue. I am new in android App development. I have connected Firebase with android studio, that's all fine except this error.
Logcat message error:
Caused by: java.lang.ClassCastException: com.google.android.gms.tasks.TaskExecutors$zza cannot be cast to android.app.Activity
at com.saqib.onlinefirregistration.VerifyOTP.sendVerificationCodeToUser(VerifyOTP.java:55)
at com.saqib.onlinefirregistration.VerifyOTP.onCreate(VerifyOTP.java:48)
VerifyOTP.java:
public class VerifyOTP extends AppCompatActivity {
//Variable
PinView pinForUser;
String codeBySystem;
Button verifyButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.verify_otp);
pinForUser = findViewById(R.id.pin_view);
verifyButton = findViewById(R.id.verify_btn);
String _PhoneNo = getIntent().getStringExtra("phoneNo");
sendVerificationCodeToUser(_PhoneNo);
}
private void sendVerificationCodeToUser(String phoneNo) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNo, // Phone No to verify
60, //timeout duration
TimeUnit.SECONDS, //Time unit
(Activity) TaskExecutors.MAIN_THREAD,
mCallback);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallback
= new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeAutoRetrievalTimeOut(#NonNull String s) {
super.onCodeAutoRetrievalTimeOut(s);
codeBySystem =s;
}
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code!=null){
pinForUser.setText(code);
verifyCode(code);
}
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(VerifyOTP.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
};
private void verifyCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codeBySystem,code);
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(VerifyOTP.this, "Verification Completed", Toast.LENGTH_SHORT).show();
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(VerifyOTP.this, "Verification Not Completed! Try Again", Toast.LENGTH_SHORT).show();
}
}
}
});
}
private void signInUsingCredential(PhoneAuthCredential credential) {
}
public void callNextScreenOTP( View view) {
String code = pinForUser.getText().toString();
if (!code.isEmpty()) {
verifyCode(code);
}
}
};
How can I fix this issue? I have no idea about it, I did search for the same question but failed to find on Google, or stack overflow.
I want to verify user through phone number verification OTP code, now I am unable to fix this issue. I am new in android App development. I have connected Firebase with android studio, that's all fine except this error.
(Activity) TaskExecutors.MAIN_THREAD line is wrong. It's clear from the error message that the cast cannot be made.
Since you're in activity, just this should do it in this place.
Just Replace: (Activity) TaskExecutors.MAIN_THREAD,
With: this,

Can't implement SMS Verification into my android app

i'm now making android apps, so here is my VerifyOTP class , I'm getting E/zzbf: SafetyNet Attestation fails basic integrity. error ...
Can Someone please help me .
this SafetyNet I just can't understand...
I've tried everything, the aplication should automatically entered Code given by SMS ... but when I enter my information in aplication, my phone number is passed by Intent ... end used in sendVerificationCodeToUser()...
public class VerifyOTP extends AppCompatActivity {
// Variables
PinView pinFromUser;
ImageView closeBtn;
String codeBySystem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_verify_o_t_p);
// Hooks
pinFromUser = findViewById(R.id.pin_view);
closeBtn = findViewById(R.id.otp_close_btn);
String _phoneNo = getIntent().getStringExtra("phone");
sendVerificationCodeToUser(_phoneNo);
closeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
VerifyOTP.super.onBackPressed();
}
});
}
private void sendVerificationCodeToUser(String phone) {
FirebaseAuth mAuth = FirebaseAuth.getInstance();
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber(phone) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(this) // Activity (for callback binding)
.setCallbacks(mCallbacks) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks =
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
codeBySystem = s;
}
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code != null) {
pinFromUser.setText(code);
verifyCode(code);
}
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(VerifyOTP.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
};
private void verifyCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codeBySystem, code);
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(VerifyOTP.this, "Verification Completed!", Toast.LENGTH_SHORT).show();
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(VerifyOTP.this, "Verification failed!", Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void CallNextFromOTP(View view) {
String code = pinFromUser.getText().toString();
if (!code.isEmpty()) {
verifyCode(code);
}
}
}
did you add at AndroidManifest.xml these permissions ?
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
i think because your code is missing premission check function that's why send you to navigation add this code to your code in VerifyOTP.java
private void checkForSmsPermission() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS) !=
PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, getString(R.string.permission_not_granted));
// Permission not yet granted. Use requestPermissions().
// MY_PERMISSIONS_REQUEST_SEND_SMS is an
// app-defined int constant. The callback method gets the
// result of the request.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
} else {
// Permission already granted. Enable the SMS button.
enableSmsButton();
}
}
Add these dependencies in your build.gradle :
implementation "androidx.browser:browser:1.3.0"
implementation "com.google.firebase:firebase-messaging:21.1.0"
Firebase Quote "The reCAPTCHA flow will only be triggered when SafetyNet is unavailable or your device does not pass suspicion checks. Nonetheless, you should ensure that both scenarios are working correctly." So to enable SafetyNet, follow the below steps or you can also visit Firebase Auth for more info.
Go to google cloud console, select your project.
Click on the navigation menu and select APis & services and then select Dashboard.
Click on enable api and services and enable api " Android Device Verification".
Add SHA 256 in firebase project settings.(debug and release both)
Download and replace the latest google-services.json file in your project.

Firebase is not sending OTP code on my Phone number | Java | Android Studio

I'm trying to authenticate user with phone number using the firebase Authentication method. But it is showing me error after some time by running the code. And I think the sendVerificationCodeToUser() function is not working properly.
package com.example.foodapp;
import ...
public class PhoneVerification<phoneAuthProvider> extends AppCompatActivity {
String verificationCodeBySystem;
Button btn_verify;
EditText phoneenteredbyuser;
ProgressBar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_verification);
btn_verify = findViewById(R.id.btn_verify);
phoneenteredbyuser = findViewById(R.id.txt_otp);
progressbar = findViewById(R.id.progressbar);
progressbar.setVisibility(View.GONE);
String phoneNo = getIntent().getStringExtra("phone");
sendVerificationCodeToUser(phoneNo);
btn_verify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code= phoneenteredbyuser.toString();
if(code.isEmpty() || code.length()< 6){
phoneenteredbyuser.setError("Wrong OTP...");
phoneenteredbyuser.requestFocus();
return;
}
progressbar.setVisibility(View.VISIBLE);
verifyCode(code);
}
});
}
private void sendVerificationCodeToUser(String phoneNo) {
FirebaseAuth mAuth= FirebaseAuth.getInstance();
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber("+92" + phoneNo) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(this) // Activity (for callback binding)
.setCallbacks(mCallbacks) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override //Entering OTP by manual way
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationCodeBySystem = s;
}
#Override // Automatically Verifying the OTP by system.
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code != null) {
progressbar.setVisibility(View.VISIBLE);
verifyCode(code);
}
}
#Override //In case of error this code will run.
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(PhoneVerification.this, "Error Occured", Toast.LENGTH_SHORT).show();
}
};
private void verifyCode(String codeByUser) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationCodeBySystem, codeByUser);
signInUserByCredentials(credential);
}
private void signInUserByCredentials(PhoneAuthCredential credential) {
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(PhoneVerification.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(PhoneVerification.this, "Your Account has been created successfully!", Toast.LENGTH_SHORT).show();
//Perform Your required action here to either let the user sign In or do something required
Intent intent = new Intent(getApplicationContext(), User_Home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else {
Toast.makeText(PhoneVerification.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}

In my code the if part is working correctly however, the else part is not executing

I am trying to set up OTP verification
I have already tried many possibilities with the if and else, however, it didn't help out.
public class userLogin extends Activity {
EditText phnNum=null, veri = null;
FirebaseAuth au;
Button forgotpass, login;
PhoneAuthProvider.OnVerificationStateChangedCallbacks otp;
String verifyCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.userlogin);
login = findViewById(R.id.loginButton);
phnNum = findViewById(R.id.enter_phone);
forgotpass = findViewById(R.id.forgot_pass);
au = FirebaseAuth.getInstance();
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((phnNum.getText().toString()).equals("")) {
(Toast.makeText(getApplicationContext(), "Please enter the phone number and proceed to receive an OTP", Toast.LENGTH_SHORT)).show();
}
else{
otp = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
}
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verifyCode = s;
(Toast.makeText(getApplicationContext(), "The OTP Code has been send, please verify the code", Toast.LENGTH_SHORT)).show();
}
};
}
}
});
}
public void send_sms (View v){
String i = (phnNum.getText()).toString();
PhoneAuthProvider.getInstance().verifyPhoneNumber(i, 60, TimeUnit.SECONDS, this, otp);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent u = new Intent(view.getContext(), otp_verify.class);
startActivity(u);
}
});
}
//SignIn Method
// We will pass value in the method with "PhoneAuthCredential" data-type.
public void SignIn(PhoneAuthCredential credential) {
//" au " is the firebase variable and call the method
au.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
(Toast.makeText(getApplicationContext(), "You have Sign-In Successfully", Toast.LENGTH_SHORT)).show();
}
else{
(Toast.makeText(getApplicationContext(), "Please try again", Toast.LENGTH_SHORT)).show();
}
}
});
}
}
When I log-in with blank EditText, the if part executes but when I enter the phone number it doesn't execute the else part. I expect the when the user enters their phone number the else part should execute.
final String i = (phnNum.getText()).toString();
if ("".equals(i)) {
(Toast.makeText(getApplicationContext(), "Please enter the phone number and proceed to receive an OTP", Toast.LENGTH_SHORT)).show();
} else {
// 1. prepare callback for async call
otp = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
}
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verifyCode = s;
(Toast.makeText(getApplicationContext(), "The OTP Code has been send, please verify the code", Toast.LENGTH_SHORT)).show();
Intent u = new Intent(userLogin.this, otp_verify.class);
startActivity(u);
}
};
// 2. execute actual call
PhoneAuthProvider.getInstance().verifyPhoneNumber(i, 60, TimeUnit.SECONDS, userLogin.this, otp);
}
The code snippet prepares callback and uses it on Firebase auth call. When the verification code is actually sent, the onCodeSent called and new activity launched.

firebase phone auth android Crashing

so I am using firebase database and Auth, I am trying to build Phone Auth but for some reason the app is crashing.. not sure why..
I am new to programming with android studio and first timer on Firebase database, not sure why the app is crashing but its crashing after I am pressing a button that activate verifySignInCode() insta crash after it, it does send an email with code a
Log cat Error is here
09-15 20:39:41.804 22046-22046/com.example.erelpc.calltest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.erelpc.calltest, PID: 22046
java.lang.IllegalArgumentException: Cannot create PhoneAuthCredential without either verificationProof, sessionInfo, ortemprary proof.
at com.google.android.gms.common.internal.Preconditions.checkArgument(Unknown Source:8)
at com.google.firebase.auth.PhoneAuthCredential.<init>(Unknown Source:6)
at com.google.firebase.auth.PhoneAuthProvider.getCredential(Unknown Source:33)
at com.example.erelpc.calltest.MainActivity.verifySignInCode(MainActivity.java:92)
at com.example.erelpc.calltest.MainActivity.access$100(MainActivity.java:28)
at com.example.erelpc.calltest.MainActivity$2.onClick(MainActivity.java:61)
at android.view.View.performClick(View.java:6877)
And Here is the MainActivity
/// SMS Handler
private void sendVerificationCode(){
String phone = etphonenumber.getText().toString();
if (phone.isEmpty()) {
etphonenumber.setError("Enter a Phone Number!");
etphonenumber.requestFocus();
return;
}
if (phone.length() != 9){
etphonenumber.setError("Please Enter a valid Number!");
etphonenumber.requestFocus();
return;
}
phone = "+972" + phone;
Intent intent = new Intent(this, loginsuccess.class);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phone, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
}
private void verifySignInCode(){
String code = etcodeveri.getText().toString();
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codesent, code);
signInWithPhoneAuthCredential(credential);
}
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(FirebaseException e) {
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
codesent = s;
}
};
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Login Success!", Toast.LENGTH_SHORT).show();
registerModule();
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(getApplicationContext(), "Login Unsuccess!", Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void registerModule(){
Intent intent = new Intent(this, loginsuccess.class);
startActivity(intent);
}
The crashing is happening after I press the "btnAdd"
The app is crashing because the method is not getting valid credential for the phoneAuth to work. This can be fixed by using try and catch on the signInWithPhoneAuthCredential() method.
In code it will look something like this:
private void verifyCode(){
String code = cd.getText().toString(); // this is OTP
String pH = phone.getText().toString(); // this is phone number
if(code.equals("") && pH.equals(""))
Toast.makeText(MainActivity.this,"Nothing to validate", Toast.LENGTH_SHORT).show();
else {
try {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(otp, code);
signInWithPhoneAuthCredential(credential);
}
catch (Exception e) {
Log.i("exception",e.toString());
Toast.makeText(MainActivity.this,"Invalid credentials",Toast.LENGTH_LONG).show();
}
}
}
Also, you should put more catch or if statements to avoid giving null value in the methods.
Just need to define String code before calling phoneAuth function.
< String code = phoneAuthCredential.getSmsCode();
assert code != null;
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, code);
signInWithPhoneAuthCredential(credential);>

Categories

Resources