Connection by phone and Firebase ID - android

I created a connection by phone number, all works very well. My only problem is that the number does not appear in the IDs on firebase.
With google auth it works very well but no with phone auth. I probably forgot something, but I can't find it.
Do you have an idea?
On firebase and gmail ID :
My activity auth phone:
public class Activity_aunth_phone extends AppCompatActivity {
EditText numero;
String verificationId;
FirebaseAuth mAuth;
Button button;
EditText cp;
private static final String TAG = "PhoneAuthActivity";
private static final String KEY_VERIFY_IN_PROGRESS = "key_verify_in_progress";
private static final int STATE_INTIALIZED = 1;
private static final int STATE_CODE_SEND = 2;
private static final int STATE_VERIFY_FAILED = 3;
private static final int STATE_VERIFY_SUCCES = 4;
private static final int STATE_SIGNIN_FAILED = 5;
private static final int STATE_SIGNIN_SUCCES = 6;
private FirebaseAuth auth;
private boolean mVerificationInProgress = false;
private String mVerificationId;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aunth_phone);
cp = findViewById(R.id.cp);
numero = (EditText) findViewById(R.id.num);
button = findViewById(R.id.button);
auth = FirebaseAuth.getInstance();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
attemptLogin();
}
});
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 verification without
// user action.
Log.d(TAG, "onVerificationCompleted:" + credential);
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.w(TAG, "onVerificationFailed", e);
if (e instanceof FirebaseAuthInvalidCredentialsException) {
// Invalid request
// ...
} else if (e instanceof FirebaseTooManyRequestsException) {
// The SMS quota for the project has been exceeded
// ...
}
// 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.d(TAG, "onCodeSent:" + verificationId);
// Save verification ID and resending token so we can use them later
mVerificationId = verificationId;
mResendToken = token;
// ...
}
};
}
private void attemptLogin() {
numero.setError(null);
String cpp = cp.getText().toString();
String number = numero.getText().toString();
String phone = cpp + number;
startPhoneNumberVerification(phone);
boolean cancel = false;
View focusView = null;
if (!isPhoneValid(phone)) {
focusView = numero;
cancel = true;
}
if (cancel) {
focusView.requestFocus();
} else {
startPhoneNumberVerification(phone);
}
}
private boolean isPhoneValid(String phone){
return phone.length() > 8;
}
private void startPhoneNumberVerification(String phoneNumber) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber,
60,
TimeUnit.SECONDS,
this,
mCallbacks);
mVerificationInProgress = true;
}
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");
Intent intent = new Intent(Activity_aunth_phone.this, Activity_profile.class);
startActivity(intent);
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
}
}
}
});
}
}

You forgot to put the Code :
private void verifyPhoneNumberWithCode(String verificationId, String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, code); // Just Pass the otp in Code Section.
signInWithPhoneAuthCredential(credential);
}
Which provide credentials to new User.
Please Check this link : https://firebase.google.com/docs/auth/android/phone-auth?authuser=1#create-a-phoneauthcredential-object

Related

Error in phone Authentication Firebase in one device

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();
}
}
});
}
}

Android fire-base OTP not verifying

I made an application to read OTP and login with mobile number,it is like in first screen user have to enter mobile number and continue at the time otp will send to the user and it goes to second activity .here user will enter otp , that otp will go to the first activity, at the end my app not verifying the otp ,please help me
public class LoginActivity extends AppCompatActivity {
EditText phonetextview;
String phone_number;
FirebaseAuth auth;
private FirebaseAuth mAuth;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private String verificationCode;
private String mVerificationId;
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
private static final String TAG ="MainActivity";
String verificationId;
String code;
// final PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
//
Intent intent = getIntent();
final String otp = intent.getStringExtra("otp");
Toast.makeText(getBaseContext(),otp,Toast.LENGTH_SHORT).show();
//getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
Toast.makeText(getBaseContext(),"hoooooooooo",Toast.LENGTH_SHORT).show();
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
System.exit(0);
}
#Override
public void onVerificationFailed(FirebaseException e) {
{
e.printStackTrace();
Toast toast = Toast.makeText(getApplicationContext(), (CharSequence) e,
Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
Log.d(TAG, "onCodeSent:" + verificationId);
mVerificationId = verificationId;
mResendToken = token;
Intent i = new Intent(getApplicationContext(),Otp.class);
startActivity(i);
// View v = (View) findViewById(R.id.phonetextview);
//((ViewManager)v.getParent()).removeView(v);
//View vv = (View) findViewById(R.id.cardView);
//((ViewManager)vv.getParent()).removeView(vv);
}
};
CardView card_view = findViewById(R.id.cardView);
card_view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
phonetextview =findViewById(R.id.phonetextview);
phone_number = PhoneNumberUtils.formatNumber(phonetextview.getText().toString());
send();
Toast toast = Toast.makeText(getApplicationContext(), phone_number,
Toast.LENGTH_SHORT);
toast.show();
}
});
}
private void send() {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
"+91"+phone_number, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // 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()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
Toast.makeText(getBaseContext(),"hoooooooooo",Toast.LENGTH_SHORT).show();
FirebaseUser user = task.getResult().getUser();
// [START_EXCLUDE]
// [END_EXCLUDE]
} 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
// [START_EXCLUDE silent]
//mVerificationField.setError("Invalid code.");
// [END_EXCLUDE]
}
// [START_EXCLUDE silent]
// Update UI
// updateUI(STATE_SIGNIN_FAILED);
// [END_EXCLUDE]
}
}
});
}
}
and this is my otp typing activity
public class Otp extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otp);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText fd = (EditText) findViewById(R.id.et1);
String value= fd.getText().toString();
// int finalValue=Integer.parseInt(value);
final EditText sd = (EditText) findViewById(R.id.et2);
String value1= sd.getText().toString();
// int finalValue1=Integer.parseInt(value1);
EditText td = (EditText) findViewById(R.id.et3);
String value2= td.getText().toString();
// int finalValue2=Integer.parseInt(value2);
EditText fod = (EditText) findViewById(R.id.et4);
String value3= fod.getText().toString();
//int finalValue3=Integer.parseInt(value3);
EditText fid = (EditText) findViewById(R.id.et5);
String value4= fid.getText().toString();
//int finalValue4=Integer.parseInt(value4);
EditText sid = (EditText) findViewById(R.id.et6);
String value5= sid.getText().toString();
//int finalValue5=Integer.parseInt(value5);
final String otp = value + value1+value2+value3+value4+value5;
Intent intent = new Intent(v.getContext(), LoginActivity.class);
intent.putExtra("otp", otp);
startActivity(intent);
finish();
}
});
}
}
If your problem is not getting OTP, then the solution is to Add SHA-1 fingerprint to your Firebase Project. This is Common Problem for so many of not getting OTP from Firebase

My firebase authentication using OTP is not working

I have a login activity where user can sign in using OTP from mobile, I used firebase for that. It was working before, but now something happened and I am not able to figure it out. Please help me. May be it can be the problem of reading phone number from text view, I installed sh1 fingerprint also.
Here is code:
public class LoginActivity extends AppCompatActivity {
EditText phonetextview;
String p;
FirebaseAuth auth;
String codesent;
String otp;
FirebaseAuth mAuth;
private PhoneAuthProvider.ForceResendingToken mResendToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
Button button = (Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText fd = (EditText) findViewById(R.id.et1);
String value= fd.getText().toString();
// int finalValue=Integer.parseInt(value);
final EditText sd = (EditText) findViewById(R.id.et2);
String value1= sd.getText().toString();
// int finalValue1=Integer.parseInt(value1);
EditText td = (EditText) findViewById(R.id.et3);
String value2= td.getText().toString();
// int finalValue2=Integer.parseInt(value2);
EditText fod = (EditText) findViewById(R.id.et4);
String value3= fod.getText().toString();
//int finalValue3=Integer.parseInt(value3);
EditText fid = (EditText) findViewById(R.id.et5);
String value4= fid.getText().toString();
//int finalValue4=Integer.parseInt(value4);
EditText sid = (EditText) findViewById(R.id.et6);
String value5= sid.getText().toString();
//int finalValue5=Integer.parseInt(value5);
otp = value + value1+value2+value3+value4+value5;
Toast.makeText(getBaseContext(),otp,Toast.LENGTH_SHORT).show();
verify();
}
});
CardView card_view = findViewById(R.id.cardView);
card_view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
send();
// Toast toast = Toast.makeText(getApplicationContext(), phone_number,
// Toast.LENGTH_SHORT);
//toast.show();
}
});
}
private void send() {
phonetextview =findViewById(R.id.phonetextview);
String p = phonetextview.getText().toString();
// phone_number = PhoneNumberUtils.formatNumber(phonetextview.getText().toString());
//int p= Integer.parseInt(phone_number) ;
//int abc = Integer.parseInt(phonetextview.getText().toString());
PhoneAuthProvider.getInstance().verifyPhoneNumber(
"+91"+p, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // ForceResendingToken from callbacks
Toast toast = Toast.makeText(getApplicationContext(),p,
Toast.LENGTH_SHORT);
toast.show();
}
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks =new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(getBaseContext(),"faild",Toast.LENGTH_SHORT).show();
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
codesent =s;
Toast.makeText(getBaseContext(),"jjj",Toast.LENGTH_LONG).show();
}
};
private void verify()
{
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codesent, otp);
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
Toast.makeText(getBaseContext(),"success",Toast.LENGTH_SHORT).show();
FirebaseUser user = task.getResult().getUser();
} else {
Toast.makeText(getBaseContext(),"ffffffffffff",Toast.LENGTH_SHORT).show();
// Sign in failed, display a message and update the UI
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// The verification code entered was invalid
}
}
}
});
}
}

Not Receiving Fire base OTP message

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)
{
}
}
}
});
}

Firebase phone authentication split into two activities

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()

Categories

Resources