I am new at android development. I am not getting OTP from firebase in my android project but I can log in using testing the phone numbers. Please look into the issue I am sharing the code shown below. Please help. I have tried this for many different mobile numbers and I also tried for the numbers that are not included in the testing phone numbers. I have also deployed it on the play store but still did not work. Thank You.
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
mVerificationInProgress = false;
signInWithPhoneAuthCredential(credential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
mVerificationInProgress = false;
if (e instanceof FirebaseAuthInvalidCredentialsException) {
} else if (e instanceof FirebaseTooManyRequestsException) {
}
}
#Override
public void onCodeSent(#NonNull String verificationId,
#NonNull PhoneAuthProvider.ForceResendingToken token) {
mVerificationId = verificationId;
mResendToken = token;
Log.d("OnCodeSent",token+"");
}
};
here I can print the token which looks good.
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
mVerificationInProgress = true;
}
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 void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = task.getResult().getUser();
Intent i = new Intent(getApplicationContext(),InitialACtivity.class);
startActivity(i);
finish();
} else {
errorOtp.setVisibility(View.VISIBLE);
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
}
}
}
});
}
private void updateUI(){
}
private boolean validatePhoneNumber() {
return true;
}
public void clickSendCode(String number){
startPhoneNumberVerification(number);
}
public void clickVerifyCode(View v){
if(mVerificationId == null){
return;
}
verifyPhoneNumberWithCode(mVerificationId, otpEntered);
}
Related
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
I'm implementing Android app that use Firebase to authenticate my users,
My problem is that after changing the Gradle dependency from:
implementation 'com.google.firebase:firebase-auth:11.8.0'
To any higher SDK version, My code stop sending SMS authentication messages..
My code:
public class AuthenticationActivity extends AppCompatActivity {
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
private EditText phoneNum;
private PinView verifyCodeET;
private String mVerificationId;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_authentication);
mAuth = FirebaseAuth.getInstance();
Button sendCodeButton = findViewById(R.id.submit1);
Button verifyCodeButton = findViewById(R.id.submit2);
phoneNum = findViewById(R.id.phonenumber);
verifyCodeET = findViewById(R.id.pinView);
sendCodeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneNumber = phoneNum.getText().toString();
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
AuthenticationActivity.this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
}
});
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
}
#Override
public void onCodeSent(String verificationId,PhoneAuthProvider.ForceResendingToken token) {
mVerificationId = verificationId;
}
};
verifyCodeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String verificationCode = verifyCodeET.getText().toString();
boolean success = true;
PhoneAuthCredential credential = null;
try {
credential = PhoneAuthProvider.getCredential(mVerificationId, verificationCode);
} catch (Exception e) {
// "Something went wrong"
success = false;
}
if (success) {
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
} else {
// "Invalid verification code"
}
}
});
}
}
This happens for any SDK version available between the current 16.1.0 to 12.0.0,
Once I'm changing back to 11.8.0 everything work as expected...
Any help will be appreciated
.
Edit
With Nouman Ch help I've added printing at onVerificationFailed() and saw the error message:
com.google.firebase.auth.FirebaseAuthInvalidCredentialsException: The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code]. [ Invalid format. ]
Using the answer from here
I've added to the Gradle file:
implementation 'com.googlecode.libphonenumber:libphonenumber:7.0.4'
implementation 'com.google.firebase:firebase-core:16.0.7'
implementation 'com.google.firebase:firebase-auth:16.1.0'
To the Java includes:
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
And edit the onClicK() function to be:
#Override
public void onClick(View view) {
String phoneNumber = phoneNum.getText().toString();
// Check phoneNumber.length()
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
PhoneNumber numberProto = phoneUtil.parse(phoneNumber, "US");
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneUtil.format(numberProto, PhoneNumberUtil.PhoneNumberFormat.E164), // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
AuthenticationActivity.this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
} catch (NumberParseException e) {
// Wrong format
}
}
Now everything work with the latest SDK version
Try e.printStackTrace(); to check which error you are getting. Use bellow code:
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
e.printStackTrace();
}
#Override
public void onCodeSent(String verificationId,PhoneAuthProvider.ForceResendingToken token) {
mVerificationId = verificationId;
}
};
Hope this will work for you.
I am new to Android development. I am not getting OTP message from Fire base but if I enter the code manually then it works. I am not sure why I am not getting text message. Your help is highly appreciated. I am not sure whether I am doing correctly sendVerificationcode method correctly or not.
Steps Completed:
1) I added GSON file to app directory
2) I added test phone number in the firebase console
3) I added SHA1 code to fire base
4) I added SMS permission in the Android manifest file.
5) I enabled firebase authentication in Android studio
6) I tried different phone numbers too
VerifyPhoneActivity.java
public class VerifyPhoneActivity extends AppCompatActivity {
private String verificationId;
private FirebaseAuth mAuth;
private ProgressBar progressBar;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verify_phone);
mAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressbar);
editText = findViewById(R.id.editTextCode);
String phonenumber = getIntent().getStringExtra("phonenumber");
sendVerificationCode(phonenumber);
findViewById(R.id.buttonSignIn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = editText.getText().toString().trim();
if (code.isEmpty() || code.length() < 6) {
editText.setError("Enter code...");
editText.requestFocus();
return;
}
verifyCode(code);
}
});
}
private void verifyCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithCredential(credential);
}
private void signInWithCredential(PhoneAuthCredential credential) {
// private void signInWithCredential(PhoneAuthCredential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Intent intent = new Intent(VerifyPhoneActivity.this, ProfileActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else {
Toast.makeText(VerifyPhoneActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
private void sendVerificationCode(String number) {
progressBar.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,
mCallBack
);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks
mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
}
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code != null) {
editText.setText(code);
verifyCode(code);
}
System.out.println("Hello Phone Number"+code);
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(VerifyPhoneActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
};
}
Below code looks like not working:
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
// String code="000000";
if (code != null) {
editText.setText(code);
verifyCode(code);
}
System.out.println("Hello Phone Number2"+code);
}
Use like this following:
onCreate
mAuth = FirebaseAuth.getInstance();
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks()
{
#Override
public void onVerificationCompleted(PhoneAuthCredential credential)
{
// This callback will be invoked in two situations:
// 1 - Instant verification. In some cases the phone number can be instantly
// verified without needing to send or enter a verification code.
// 2 - Auto-retrieval. On some devices Google Play services can automatically
// detect the incoming verification SMS and perform verificaiton without
// user action.
Log.d(TAG, "onVerificationCompleted:" + credential);
Log.e("number","credential=-=-=>>><<>>>signInWithPhoneAuthCredential-->>");
signInWithPhoneAuthCredential(credential);
}
#Override
public void onVerificationFailed(FirebaseException e)
{
// This callback is invoked in an invalid request for verification is made,
// for instance if the the phone number format is not valid.
Log.e(TAG, "onVerificationFailed", e);
// Show a message and update the UI
// ...
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token)
{
// The SMS verification code has been sent to the provided phone number, we
// now need to ask the user to enter the code and then construct a credential
// by combining the code with a verification ID.
Log.e(TAG, "onCodeSent:" + verificationId+"<<token>>"+token);
// Save verification ID and resending token so we can use them later
mVerificationId = verificationId;
//mResendToken = token;
// ...
}
};
//String phoneNumber=Settings.PREFIX + Settings.PREFIX_PHONE;
String phoneNumber="your phone number with prefix";
Log.e("number","credential=-=-=>>>22222>>"+phoneNumber);
if(phoneNumber!=null && !phoneNumber.isEmpty())
{
startPhoneNumberVerification(phoneNumber);
}
Method:
private void startPhoneNumberVerification(String phoneNumber)
{
Log.e("startPhoneNumber","startPhoneNumberVerification------>>"+phoneNumber);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
Log.e("startPhoneNumber","startPhoneNumberVerification--2222222---->>"+phoneNumber);
}
Method:
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.e(TAG, "signInWithCredential:success");
} else
{
// Sign in failed, display a message and update the UI
Log.e(TAG, "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException)
{
}
}
}
});
}
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();