My firebase authentication using OTP is not working - android

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

Related

the firebase reference is not being added

for some reason, the data is not being added to the firebase database. maybe its because i set the database in test mode? i have no idea. this was working before, however today it stopped working.
private EditText EditTextFullName, EditTextAge, EditTextEmail, EditTextPassword;
private TextView registerUser;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mAuth = FirebaseAuth.getInstance();
Objects.requireNonNull(getSupportActionBar()).hide();
EditTextFullName = (EditText) findViewById(R.id.fullName);
EditTextAge = (EditText) findViewById(R.id.age);
EditTextEmail = (EditText) findViewById(R.id.email);
EditTextPassword = (EditText) findViewById(R.id.password);
registerUser= (Button) findViewById(R.id.registerUser);
registerUser.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.registerUser:
registerUser();
break;
}
}
private void registerUser() {
String email = EditTextEmail.getText().toString().trim();
String age = EditTextAge.getText().toString().trim();
String fullname = EditTextFullName.getText().toString().trim();
String password = EditTextPassword.getText().toString().trim();
if(password.length() < 6) {
EditTextPassword.setError("Min password length should be 6 characters");
EditTextPassword.requestFocus();
return;
}
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
User user = new User(fullname, age, email);
FirebaseDatabase.getInstance().getReference("Users")
.child((FirebaseAuth.getInstance().getCurrentUser()).getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText(Register.this, "User has been registered", Toast.LENGTH_LONG).show();
startActivity(new Intent(Register.this,Login.class));
} else
{
Toast.makeText(Register.this, "Failed to register", Toast.LENGTH_LONG).show();
}
};
});
}
}
});
}
}
Well it turns out that I completely flopped when writing my code. Turns out in my User class with my constructers, i had my strings there twice causing the database to not know what to use.

Firebase not sending auth code to mobile for mobile verfication

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

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

Can't pass null for argument 'pathString' in child() at com.google.firebase.database.DatabaseReference.child(Unknown Source:40) [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am creating an android app to login the users by using Mobile number OTP verification from fire-base This is how the database looks like
This is the loggin activity where i am passing the value "mobile" to OTP typing activity( here LoginActivity.java)
CardView card_view = findViewById(R.id.cardView);
card_view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mobile = editTextMobile.getText().toString().trim();
if(mobile.isEmpty() || mobile.length() < 10){
editTextMobile.setError("Enter a valid mobile");
editTextMobile.requestFocus();
return;
}
if(mobile.length()>10)
{
editTextMobile.setError("Enter a valid mobile");
editTextMobile.requestFocus();
return;
}
Intent intent = new Intent(LoginActivity.this, VerifyPhoneActivity.class);
intent.putExtra("mobile", mobile);
startActivity(intent);
}
});
This is where user will enter the OTP (VerifyPhoneActivity.java). If the OTP is correct and if the mobile number is not exist in database already then user can go to sigh up up activity
public FirebaseAuth.AuthStateListener authListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verify_phone);
mAuth= FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference();
sendVerificationCode();
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
verifySignInCode();
}
});
}
private void verifySignInCode()
{
final EditText fd = (EditText) findViewById(R.id.et1);
String value= fd.getText().toString();
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();
EditText fod = (EditText) findViewById(R.id.et4);
String value3= fod.getText().toString();
EditText fid = (EditText) findViewById(R.id.et5);
String value4= fid.getText().toString();
EditText sid = (EditText) findViewById(R.id.et6);
String value5= sid.getText().toString();
code = value + value1+value2+value3+value4+value5;
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codesent, code);
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
FirebaseUser userid = FirebaseAuth.getInstance().getCurrentUser();
final String uid = userid.getUid();
ref.child("Users");
ref.child(mobile).child(uid);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Toast.makeText(getApplicationContext(), "already account there",
Toast.LENGTH_LONG).show();
} else {
Intent intent = new Intent(VerifyPhoneActivity.this, Signup.class);
intent.putExtra("mobile", mobile);
startActivity(intent);
Intent myIntent = new Intent(VerifyPhoneActivity.this, Signup.class);
startActivity(myIntent);
Toast.makeText(getApplicationContext(), "account not exist",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Toast.makeText(getApplicationContext(), "login success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "login faild",
Toast.LENGTH_LONG).show();
// 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(getApplicationContext(), "OTP was wrong",
Toast.LENGTH_LONG).show();
}
}
}
});
}
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks=new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
Toast.makeText(getApplicationContext(), "verification completed",
Toast.LENGTH_LONG).show();
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(getApplicationContext(), "sending faild"+e,
Toast.LENGTH_LONG).show();
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
// super.onCodeSent(s, forceResendingToken);
Toast.makeText(getApplicationContext(), "sent",
Toast.LENGTH_LONG).show();
codesent=s;
}
};
private void sendVerificationCode() {
Intent intent = getIntent();
mobile = intent.getStringExtra("mobile");
Toast.makeText(getApplicationContext(), mobile,
Toast.LENGTH_LONG).show();
String phonenumber= "+91"+mobile;
// Toast.makeText(getApplicationContext(), phonenumber,
// Toast.LENGTH_LONG).show();
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phonenumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
}
}
And at last this is where (Signup.java) am getting error (i will mension below)
public class Signup extends Activity {
String name;
String address;
String pincode;
String city;
String mobile;
DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
Intent intent = getIntent();
mobile = intent.getStringExtra("mobile");
findViewById(R.id.signupbutton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText nameedittext = (EditText) findViewById(R.id.nametextview);
name= nameedittext.getText().toString();
EditText addressedittext = (EditText) findViewById(R.id.addresstextview);
address= addressedittext.getText().toString();
EditText pincodeedittext = (EditText) findViewById(R.id.picodetextview);
pincode= pincodeedittext.getText().toString();
EditText cityedittext = (EditText) findViewById(R.id.citytextview);
city= cityedittext.getText().toString();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref = ref.child("Users");
FirebaseUser userid = FirebaseAuth.getInstance().getCurrentUser();
final String uid = userid.getUid();
ref = ref.child(mobile).child(uid);
Map<String, String> userData = new HashMap<String, String>();
userData.put("Name", name);
userData.put("Address", address);
userData.put("Pin", pincode);
userData.put("City", city);
ref.setValue(userData);
}
});
}
}
I am facing 2 problems
I am getting the error below and app crashes app relaunching the same activity (Signup.java) if i enter the details again it will get updated in db as screenshot above (in case i am the first user)
If the first user signed up and his mobile got registered then when the second user sign up it is showing "login success" and account "already there" 2 toasts
Error am getting
2019-03-15 16:57:40.706 1932-1932/com.example.meenvandi E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.meenvandi, PID: 1932
java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
at com.google.firebase.database.DatabaseReference.child(Unknown Source:40)
at com.example.meenvandi.Signup$1.onClick(Signup.java:78)
at android.view.View.performClick(View.java:6330)
at android.view.View$PerformClick.run(View.java:25136)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:192)
at android.app.ActivityThread.main(ActivityThread.java:6778)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:875)
I am just starting android and this project is very very impotent for me please help if i you can identify the problem which i am unable to
One of the variables are null, its either mobile or uid, you can try to print both variables out to know which one is null.
My guess is you are trying to save a user in the db and this user haven't logged in to firebase before so uid will be null

Firebase not sending SMS Android Studio

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 .

Categories

Resources