public class MainActivity extends AppCompatActivity {
EditText editTextPhone, editTextCode;
FirebaseAuth mAuth;
String codeSent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
editTextCode = findViewById(R.id.editTextCode);
editTextPhone = findViewById(R.id.editTextPhone);
findViewById(R.id.buttonGetVerificationCode).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendVerificationCode();
}
});
findViewById(R.id.buttonSignIn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
verifySignInCode();
}
});
}
private void verifySignInCode(){
String code = editTextCode.getText().toString();
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codeSent, code);
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//here you can open new activity
Toast.makeText(getApplicationContext(),
"Login Successfull", Toast.LENGTH_LONG).show();
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(getApplicationContext(),
"Incorrect Verification Code ", Toast.LENGTH_LONG).show();
}
}
}
});
}
private void sendVerificationCode(){
String phone = editTextPhone.getText().toString();
if(phone.isEmpty()){
editTextPhone.setError("Phone number is required");
editTextPhone.requestFocus();
return;
}
if(phone.length() < 10 ){
editTextPhone.setError("Please enter a valid phone");
editTextPhone.requestFocus();
return;
}
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) {
}
#Override
public void onVerificationFailed(FirebaseException e) {
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
codeSent = s;
}
};
}
Firebase not sending a auth code to mobile for verification please check what is the problem
because if your already regiter a number then 2nd time doesnot send if you want to try them to get otp then delete a number from firebase auth and try again
Related
My App having the Phone authentication method for user register and login to firebase is working fine for some devices but in one device it had send the verification SMS only the first time i checked it. After that ,I even deleted that account from firebase console but it is not sending any verfication code on registering that number again.
public class phone_no_verification extends AppCompatActivity {
ProgressBar verify_progress;
TextInputEditText verify_edittext;
TextInputLayout verify_textInput;
String mverificationID;
FirebaseAuth auth;
static String TAG;
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_no_verification);
verify_progress = findViewById(R.id.verify_progress);
verify_edittext = findViewById(R.id.verify_edittext);
verify_textInput = findViewById(R.id.verify_textinputLayout);
auth = FirebaseAuth.getInstance();
//getting Intent mobile number
Intent intent = getIntent();
String mobile = intent.getStringExtra("mobile_no");
sendVerificationcode(mobile);
//Entering code manually
findViewById(R.id.verify_Button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = verify_edittext.getText().toString().trim();
if(code.isEmpty() || code.length() < 6){
verify_textInput.setError("Enter Valid code");
}
else{
verifyVerificationCode(code);}
}
});
}
private void sendVerificationcode(String mobile) {
PhoneAuthProvider.getInstance().verifyPhoneNumber
("+91" + mobile,60, TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,mcallbacks);
}
//callback to detect verification status
PhoneAuthProvider.OnVerificationStateChangedCallbacks mcallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
mverificationID = s;
}
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
Log.d(TAG, "onVerificationCompleted:" + phoneAuthCredential);
String code = phoneAuthCredential.getSmsCode();
if(code != null){
verify_edittext.setText(code);
verifyVerificationCode(code);
}
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(phone_no_verification.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
};
private void verifyVerificationCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mverificationID,code);
//signing user
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
auth.signInWithCredential(credential).addOnCompleteListener(phone_no_verification.this
, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Intent intent = new Intent(phone_no_verification.this, Basic_activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
sp = getSharedPreferences("login",MODE_PRIVATE);
sp.edit().putBoolean("isAutheticated",true).apply();
}
else{
String message = "Somthing is wrong, we will fix it soon...";
if(task.getException() instanceof FirebaseAuthInvalidCredentialsException){
message = "Invalid code Entered..";
}
else if(task.getException() instanceof FirebaseAuthUserCollisionException){
message = "User Already Exists";
}
Toast.makeText(phone_no_verification.this,message,Toast.LENGTH_LONG).show();
}
}
});
}
}
I am trying to verify phone number, but it fails all time. I have Login Activity which takes mobile number. After click on login button I want OTP activity will open and user can enter OTP here and click on verify button to verify the number. But it always goes on onVerificationFailed block and shows toast Verification Fail and Invalid Number.
Login activity
public class LoginMain extends AppCompatActivity {
public FirebaseAuth mAuth;
// [END declare_auth]
public String mVerificationId;
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
public PhoneAuthProvider.ForceResendingToken mResendToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_main);
final EditText txtMobileno = (EditText) findViewById(R.id.txtMobileno);
Button btnLogin = (Button) findViewById(R.id.btnLogin);
mAuth = FirebaseAuth.getInstance();
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
Toast.makeText(LoginMain.this, "Verification Done" + phoneAuthCredential, Toast.LENGTH_LONG).show();
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(LoginMain.this, "Verification Fail", Toast.LENGTH_LONG).show();
if (e instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(LoginMain.this, "Invalid Number", Toast.LENGTH_SHORT).show();
} else if (e instanceof FirebaseTooManyRequestsException) {
Toast.makeText(LoginMain.this, "Too many Request", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
mVerificationId = s;
mResendToken = forceResendingToken;
Toast.makeText(LoginMain.this, "Code Sent", Toast.LENGTH_SHORT).show();
}
};
txtMobileno.setText("+"+getCountrycode());
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String mobileno = txtMobileno.getText().toString();
PhoneAuthProvider.getInstance().verifyPhoneNumber( mobileno, 60, TimeUnit.SECONDS, LoginMain.this, mCallbacks);
}
});
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.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 informatio
Toast.makeText(LoginMain.this, "Verification done", Toast.LENGTH_LONG).show();
FirebaseUser user = task.getResult().getUser();
// ...
} else {
// Sign in failed, display a message and update the UI
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// The verification code entered was invalid
Toast.makeText(LoginMain.this, "Verification failed code invalid", Toast.LENGTH_LONG).show();
}
}
}
});
}
}
OTP activity
public class OTP extends AppCompatActivity {
public FirebaseAuth mAuth;
public String mVerificationId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otp);
mAuth = FirebaseAuth.getInstance();
Button btnVerify = (Button) findViewById(R.id.btnVerifyOTP);
final EditText txtOtp = (EditText) findViewById(R.id.txtOtp);
btnVerify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential( mVerificationId , txtOtp.getText().toString());
signInWithPhoneAuthCredential(credential);
}
});
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.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, "signInWithCredential:success");
Toast.makeText(OTP.this,"Verification done",Toast.LENGTH_LONG).show();
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
Toast.makeText(OTP.this,"Verification failed code invalid",Toast.LENGTH_LONG).show();
}
}
}
});
}
}
Error:
[FirebaseAuth: ] getGoogleApiForMethod() returned Gms
Verification Fail or Invalid Number usually happens either when Phone number you sent is in an invalid format or you may be have missed the correct google_service.json file.
One simple format includes sending phone number with the correct country code. Please add the code and send. Hope this works.
I'm creating an app for Android phones and using Firebase OTP authentication but I'm not sure if the codes are wrong or there's really an issue with Firebase sending SMS as what I've read as I have searched so far. Any help would be greatly appreciated!
This is the code:
public class MainActivity extends AppCompatActivity {
Button btSendCode;
Button btResend;
Button btVerify;
EditText etPhoneNumber;
EditText etEnterCode;
TextView tvGoHere;
String phoneVerificationID;
FirebaseAuth auth;
PhoneAuthProvider.OnVerificationStateChangedCallbacks verificationCallbacks;
PhoneAuthProvider.ForceResendingToken resendToken;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btSendCode = (Button) findViewById(R.id.button_sendcode);
btResend = (Button) findViewById(R.id.button_resend);
btVerify = (Button) findViewById(R.id.button_verify);
etPhoneNumber = (EditText) findViewById(R.id.edittext_phonenumber);
etEnterCode = (EditText) findViewById(R.id.edittext_entercode);
tvGoHere = (TextView) findViewById(R.id.textview_gohere);
auth = FirebaseAuth.getInstance();
}
public void clickSendCode(View view) {
etPhoneNumber.setVisibility(View.INVISIBLE);
btSendCode.setVisibility(View.INVISIBLE);
etEnterCode.setVisibility(View.VISIBLE);
btResend.setVisibility(View.VISIBLE);
btVerify.setVisibility(View.VISIBLE);
//firebase code
String phoneNumber = etPhoneNumber.getText().toString();
setUpVerificationCallbacks();
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber,
120,
TimeUnit.SECONDS,
this,
verificationCallbacks
);
}
public void setUpVerificationCallbacks() {
verificationCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
signInWithPhoneAuthCredential(credential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
if(e instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(MainActivity.this, "Invalid phone format", Toast.LENGTH_SHORT).show();
} else if(e instanceof FirebaseTooManyRequestsException) {
Toast.makeText(MainActivity.this, "Too many requests", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCodeSent(String verificationID, PhoneAuthProvider.ForceResendingToken token) {
phoneVerificationID = verificationID;
resendToken = token;
}
};
}
public void clickVerifyCode(View view) {
String code = etEnterCode.getText().toString();
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(phoneVerificationID, code);
signInWithPhoneAuthCredential(credential);
}
public void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
auth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
FirebaseUser user = task.getResult().getUser();
} else {
if(task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(MainActivity.this, "Invalid code", Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void clickResendCode(View view) {
String phoneNumber = etPhoneNumber.getText().toString();
setUpVerificationCallbacks();
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber,
120,
TimeUnit.SECONDS,
this,
verificationCallbacks,
resendToken
);
}
public void onClickGoHere(View view) {
Intent intentLogin = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intentLogin);
}
}
Phone number must begin with +, followed by country code and followed by number. Example: +9195021*****. And enable phone authentication sign method .
I am doing a Phone Auth Login for android studio using Firebase, My java and XML code works for the First Activity but when I try to split it up so that it works using Second Activity it crashes.
The First Activity is for receiving the user's number and once the user has entered the number and presses "send" the user is taken to the Second Activity which validates the auth code and resends the code, I am able to get the code to be sent from the first page but when I go to the second page and enter it the app crashes. When I try to debug I get null values in both the edit text fields.
public class PhoneAuthActivity extends AppCompatActivity implements
View.OnClickListener {
private static final String TAG = "PhoneAuthActivity";
private UserInformation mUser;
EditText mVerificationField,mPhoneNumberField;
Button mStartButton;
private FirebaseAuth mAuth;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_in2);
mUser = new UserInformation();
// Assign views
mPhoneNumberField = (EditText) findViewById(R.id.PhoneNumber);
mStartButton = (Button) findViewById(R.id.Start_Verification);
mStartButton.setOnClickListener(this);
mAuth = FirebaseAuth.getInstance();
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
Log.d(TAG, "onVerificationCompleted:" + credential);
signInWithPhoneAuthCredential(credential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
Log.w(TAG, "onVerificationFailed", e);
if (e instanceof FirebaseAuthInvalidCredentialsException) {
mPhoneNumberField.setError("Invalid phone number.");
} else if (e instanceof FirebaseTooManyRequestsException) {
Toast.makeText(PhoneAuthActivity.this, "Quota exceeded", Toast.LENGTH_LONG).show();
}
}
};
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = task.getResult().getUser();
startActivity(new Intent(PhoneAuthActivity.this, Name_Activity.class));
finish();
} else {
Log.w(TAG, "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
mVerificationField.setError("Invalid code.");
}
}
}
});
}
private void verifyPhoneNumberWithCode(String verificationId, String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
//signInWithPhoneAuthCredential(credential);
}
private void startPhoneNumberVerification(String phoneNumber) {
mUser.setPhone_num(phoneNumber);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
}
private boolean validatePhoneNumber() {
String phoneNumber = mPhoneNumberField.getText().toString();
if (TextUtils.isEmpty(phoneNumber)) {
mPhoneNumberField.setError("Invalid phone number.");
return false;
}
return true;
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.Start_Verification:
if (!validatePhoneNumber()) {
return;
}
startPhoneNumberVerification(mPhoneNumberField.getText().toString());
startActivity(new Intent(PhoneAuthActivity.this,
PhoneVerAuthActivity.class));
finish();
break;
}
}
}
the second activity
public class PhoneVerAuthActivity extends AppCompatActivity implements
View.OnClickListener {
private static final String TAG = "PhoneAuthActivity";
String phone;
EditText mVerificationField,mPhoneNumberField;
Button mVerifyButton, mResendButton;
String mVerificationId;
private FirebaseAuth mAuth;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
private UserInformation mUser;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_in3);
mUser = new UserInformation();
// Assign views
mVerificationField = (EditText) findViewById(R.id.NumVer);
mVerifyButton = (Button) findViewById(R.id.btnVerify);
mResendButton = (Button) findViewById(R.id.btnresend);
mVerifyButton.setOnClickListener(this);
mResendButton.setOnClickListener(this);
mAuth = FirebaseAuth.getInstance();
phone = mUser.getPhone_num();
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
Log.d(TAG, "onVerificationCompleted:" + credential);
signInWithPhoneAuthCredential(credential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
Log.w(TAG, "onVerificationFailed", e);
if (e instanceof FirebaseAuthInvalidCredentialsException) {
mPhoneNumberField.setError("Invalid phone number.");
} else if (e instanceof FirebaseTooManyRequestsException) {
Toast.makeText(PhoneVerAuthActivity.this, R.string.Quota_exceeded, Toast.LENGTH_LONG).show();
}
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
Log.d(TAG, "onCodeSent:" + verificationId);
mVerificationId = verificationId;
mResendToken = token;
}
};
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = task.getResult().getUser();
startActivity(new Intent(PhoneVerAuthActivity.this, Name_Activity.class));
finish();
} else {
Log.w(TAG, "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
mVerificationField.setError(getString(R.string.Invalid_code));
}
}
}
});
}
private void verifyPhoneNumberWithCode(String verificationId, String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithPhoneAuthCredential(credential);
}
private void resendVerificationCode(String phoneNumber,
PhoneAuthProvider.ForceResendingToken token) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks, // OnVerificationStateChangedCallbacks
token); // ForceResendingToken from callbacks
}
private boolean validatePhoneNumber() {
String phoneNumber = mVerificationField.getText().toString();
if (TextUtils.isEmpty(phoneNumber)) {
mVerificationField.setError(getString(R.string.Invalid_phonenumber));
return false;
}
return true;
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnVerify:
String code = mVerificationField.getText().toString();
if (TextUtils.isEmpty(code)) {
mVerificationField.setError(getString(R.string.cannot_be_empty));
return;
}
verifyPhoneNumberWithCode(mVerificationId, code);
break;
case R.id.btnresend:
resendVerificationCode(phone, mResendToken);
break;
}
}
}
UserInformation
public class UserInformation {
private String name;
private String phone_num;
public UserInformation()
{
}
public UserInformation (String name)
{
this.name = name;
//this.phone_num = phone_num
}
public String getPhone_num(){
return phone_num;
}
public void setPhone_num(String phone_num){
this.phone_num = phone_num;
}
public String getName() { return name; }
public void setName(String name) { this.name = name;}
}
Process: com.example.bogle.chatdemo2, PID: 32609
java.lang.IllegalArgumentException: Given String is empty or null
at com.google.android.gms.common.internal.zzbo.zzcF(Unknown Source)
at com.google.firebase.auth.PhoneAuthCredential.<init>(Unknown Source)
at com.google.firebase.auth.PhoneAuthProvider.getCredential(Unknown Source)
at com.example.bogle.chatdemo2.PhoneVerAuthActivity.verifyPhoneNumberWithCode(PhoneVerAuthActivity.java:127)
at com.example.bogle.chatdemo2.PhoneVerAuthActivity.onClick(PhoneVerAuthActivity.java:181)
at android.view.View.performClick(View.java:6205)
at android.widget.TextView.performClick(TextView.java:11103)
at android.view.View$PerformClick.run(View.java:23653)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
You initiate new mUser object.
mUser = new UserInformation();
Then trying to get getPhone_num() from it but there is no phone number in it.
mUser.getPhone_num();
You have to pass FirebaseUser user in intent while starting second activity and then get User object from getIntent()
This is my activity that displays edit text fields for verification code and phone number. On click of start button I am not getting any response.
Thanks in advance.
EditText mPhoneNumberField, mVerificationField;
Button mStartButton, mVerifyButton, mResendButton;
private FirebaseAuth mAuth;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
String mVerificationId;
private static final String TAG = "PhoneAuthActivity";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone);
mPhoneNumberField = (EditText) findViewById(R.id.field_phone_number);
mVerificationField = (EditText) findViewById(R.id.field_verification_code);
mStartButton = (Button) findViewById(R.id.button_start_verification);
mVerifyButton = (Button) findViewById(R.id.button_verify_phone);
mResendButton = (Button) findViewById(R.id.button_resend);
mStartButton.setOnClickListener(this);
mVerifyButton.setOnClickListener(this);
mResendButton.setOnClickListener(this);
mAuth = FirebaseAuth.getInstance();
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
Log.d(TAG, "onVerificationCompleted:" + credential);
signInWithPhoneAuthCredential(credential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
Log.w(TAG, "onVerificationFailed", e);
if (e instanceof FirebaseAuthInvalidCredentialsException) {
mPhoneNumberField.setError("Invalid phone number.");
} else if (e instanceof FirebaseTooManyRequestsException) {
Snackbar.make(findViewById(android.R.id.content), "Quota exceeded.",
Snackbar.LENGTH_SHORT).show();
}
}
#Override
public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) {
Log.d(TAG, "onCodeSent:" + verificationId);
mVerificationId = verificationId;
mResendToken = token;
}
};
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = task.getResult().getUser();
startActivity(new Intent(PhoneNumberActivity.this, MainActivity.class));
finish();
} else {
Log.w(TAG, "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
mVerificationField.setError("Invalid code.");
}
}
}
});
}
private void startPhoneNumberVerification(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
}
private void verifyPhoneNumberWithCode(String verificationId, String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithPhoneAuthCredential(credential);
}
private void resendVerificationCode(String phoneNumber,
PhoneAuthProvider.ForceResendingToken token) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks, // OnVerificationStateChangedCallbacks
token); // ForceResendingToken from callbacks
}
private boolean validatePhoneNumber() {
String phoneNumber = mPhoneNumberField.getText().toString();
if (TextUtils.isEmpty(phoneNumber)) {
mPhoneNumberField.setError("Invalid phone number.");
return false;
}
return true;
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
startActivity(new Intent(PhoneNumberActivity.this, MainActivity.class));
finish();
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button_start_verification:
if (!validatePhoneNumber()) {
return;
}
startPhoneNumberVerification(mPhoneNumberField.getText().toString());
break;
case R.id.button_verify_phone:
String code = mVerificationField.getText().toString();
if (TextUtils.isEmpty(code)) {
mVerificationField.setError("Cannot be empty.");
return;
}
verifyPhoneNumberWithCode(mVerificationId, code);
break;
case R.id.button_resend:
resendVerificationCode(mPhoneNumberField.getText().toString(), mResendToken);
break;
}
}
This is my code. But it is giving the following exception:
com.google.firebase.FirebaseNetworkException: A network error (such as timeout, interrupted connection or unreachable host) has occurred.
Try
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser()
instead of
FirebaseUser currentUser = mAuth.getCurrentUser();