firebase phone number authentication getting null reference - java

I am trying to create a phone number logging section in my application so that the user can log in using the phone number. I am trying to run my application on the physical device when I try to login using the phone number and received an error says the null reference. I have searched for the solution all over the internet but didn't get any proper solution to remove this error. I have allowed the phone authentication in firebase still, I am getting the error. I have used the country picker in my activity to get the country code and it works file.
Error occurs in
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phonestring,
60,
TimeUnit.SECONDS,
Phoneactivity.this,
mCallbacks
);
Phoneactivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phoneactivity);
mAuth = FirebaseAuth.getInstance();
initalization();
phonenumbermethod();
emailloginmethod();
}
private void emailloginmethod() {
emaillogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),Loginactivity.class);
startActivity(intent);
}
});
}
private void phonenumbermethod() {
if(REQUEST.equals("phone")){
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
REQUEST = "OTP";
String phonenumberstring = phone.getText().toString();
String countrycode = ccp.getSelectedCountryCodeWithPlus();
phonestring = countrycode + phonenumberstring;
//Toast.makeText(getApplicationContext(),phonestring,Toast.LENGTH_SHORT).show();
verificationcodesend();
}
});
}else{
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
REQUEST = "phone";
otpstring = otp.getText().toString();
otpmethod();
}
});
}
}
private void otpmethod() {
if (TextUtils.isEmpty(otpstring)){
Toast.makeText(getApplicationContext(),"Please enter the verification code", Toast.LENGTH_SHORT).show();
}else{
loadingBar.setTitle("Verification code");
loadingBar.setMessage("Please wait...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, otpstring);
signInWithPhoneAuthCredential(credential);
}
}
private void verificationcodesend() {
if(TextUtils.isEmpty(phonestring)){
Toast.makeText(getApplicationContext(),"Please enter phone number",Toast.LENGTH_SHORT).show();
}else{
loadingBar.setTitle("Phone verification");
loadingBar.setMessage("Please wait till we verify your account");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
Log.i("phoneactivity",phonestring);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phonestring,
60,
TimeUnit.SECONDS,
Phoneactivity.this,
mCallbacks
);
}
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
loadingBar.dismiss();
Toast.makeText(getApplicationContext(),"Please enter the correct phone number", Toast.LENGTH_SHORT).show();
}
#Override
public void onCodeSent(#NonNull String verificationId,
#NonNull PhoneAuthProvider.ForceResendingToken token) {
loadingBar.dismiss();
mVerificationId = verificationId;
mResendToken = token;
Toast.makeText(getApplicationContext(),"Verification code has been send", Toast.LENGTH_SHORT).show();
otpnumber.setVisibility(View.VISIBLE);
phonenumber.setVisibility(View.GONE);
}
};
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
loadingBar.dismiss();
sendusertomainActivity();
Toast.makeText(getApplicationContext(),"welcome",Toast.LENGTH_SHORT).show();
} else {
String msg = task.getException().toString();
Toast.makeText(getApplicationContext(),"Error: "+ msg, Toast.LENGTH_SHORT).show();
}
}
});
}
private void sendusertomainActivity() {
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
startActivity(intent);
}
error: null reference
java.lang.NullPointerException: null reference
at com.google.android.gms.common.internal.Preconditions.checkNotNull(Unknown Source:2)
at com.google.firebase.auth.PhoneAuthProvider.verifyPhoneNumber(com.google.firebase:firebase-auth##19.2.0:9)
at com.nanb.Alpha.Phoneactivity.verificationcodesend(Phoneactivity.java:109)
at com.nanb.Alpha.Phoneactivity.access$300(Phoneactivity.java:28)
at com.nanb.Alpha.Phoneactivity$2.onClick(Phoneactivity.java:72)
at android.view.View.performClick(View.java:6608)
at android.view.View.performClickInternal(View.java:6585)
at android.view.View.access$3100(View.java:785)
at android.view.View$PerformClick.run(View.java:25921)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6864)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
update
2020-03-15 21:03:00.382 30384-30384/com.nanb.Alpha I/phoneactivity: +919771553694

You're not initializing mCallback before passing it into verifyPhoneNumber, which is what the null check is complaining about.
To fix it, move the mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {... before the call to verifyPhoneNumber.

Related

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

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

Android studio : FATAL EXCEPTION: main

while I testing my app, I get the following error in the Android-Studio-logcat:
before getting this error, I was clicked on setPositiveButton of alert Dialog Button name is "EMAIL ME" with empty EditText.
and then I got Unfortunately twist has stopped.
please I need help!!
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.testing.twist, PID: 30072
java.lang.IllegalArgumentException: Given String is empty or null
at com.google.android.gms.common.internal.Preconditions.checkNotEmpty(Unknown
Source)
at com.google.firebase.auth.FirebaseAuth.sendPasswordResetEmail(com.google.firebase:firebase-auth##19.3.1:307)
at com.testing.twist.login.beginforgotpasswd(login.java:141)
at com.testing.twist.login.access$400(login.java:26)
at com.testing.twist.login$4.onClick(login.java:119)
at androidx.appcompat.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5268)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
here is some code of my login.java file
public class login extends AppCompatActivity {
private EditText Email;
private EditText password;
private Button btn_login;
private TextView tv_signup;
private FirebaseAuth firebaseAuth;
private TextView tv_forgotpasswd_l;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Email = (EditText)findViewById(R.id.et_email_l);
password = (EditText)findViewById(R.id.et_passwd_l);
btn_login = (Button)findViewById(R.id.btn_l);
tv_signup = (TextView)findViewById(R.id.tv_sign_up);
tv_forgotpasswd_l = (TextView)findViewById(R.id.tv_f_passwd);
firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null){
finish();
startActivity(new Intent(login.this, MainActivity.class));
}
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(Email.getText().toString(), password.getText().toString());
}
});
tv_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(login.this,Register.class));
}
});
// Login button hide
Email.addTextChangedListener(loginTextWatcher);
password.addTextChangedListener(loginTextWatcher);
// recover pass textview click
tv_forgotpasswd_l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showForgotpasswdDialog();
}
});
}
// Alert Dialog
private void showForgotpasswdDialog()
{
//Dialog Box code
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Forgot your password?");
//set linear layout
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(30,30,30,30);
Email.setPadding(10,10,10,10);
//view to set an dialog
final EditText Email = new EditText(this);
Email.setHint("Email");
Email.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
//text view
linearLayout.addView(Email);
builder.setView(linearLayout);
//text style
// Text view
final TextView tv = new TextView(this);
tv.setTextSize(14);
tv.setTypeface(null, Typeface.BOLD);
tv.setTextColor(Color.parseColor("black"));
tv.setText("Unfortunately, if you have never given us your email, we will not be able to reset your password.");
tv.setPadding(10,10,10,10);
linearLayout.addView(tv);
builder.setView(linearLayout);
//buttons for EMAIL ME
builder.setPositiveButton("EMAIL ME", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//input email
String email = Email.getText().toString().trim();
beginforgotpasswd(email);
}
});
//buttons for CANCEL
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
// dismiss dialog
dialog.dismiss();
}
});
///show dialog
builder.create().show();
}
private void beginforgotpasswd(String email)
{
firebaseAuth.sendPasswordResetEmail(email).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(login.this,"Email sent",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(login.this,"Failed...",Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//get and show proper error message
Toast.makeText(login.this,""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
private TextWatcher loginTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String emailInput = Email.getText().toString().trim();
String passwdInput = password.getText().toString().trim();
btn_login.setEnabled(!emailInput.isEmpty() && !passwdInput.isEmpty());
}
#Override
public void afterTextChanged(Editable editable) {
}
};
private void validate(String usremail, String usrpassword){
firebaseAuth.signInWithEmailAndPassword(usremail,usrpassword).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(Task<AuthResult> task) {
if(task.isSuccessful()){
//Toast.makeText(login.this, "Login Successful",Toast.LENGTH_SHORT).show();
checkEmailVerification();
}
else{
Toast.makeText(login.this, "Login Failed",Toast.LENGTH_SHORT).show();
}
}
});
}
private void checkEmailVerification()
{
FirebaseUser firebaseUser = firebaseAuth.getInstance().getCurrentUser();
Boolean emailflag = firebaseUser.isEmailVerified();
if(emailflag)
{
finish();
startActivity(new Intent(login.this,MainActivity.class));
}
else
{
Toast.makeText(login.this, "Verify your email", Toast.LENGTH_SHORT).show();
firebaseAuth.signOut();
}
}
}
The call to firebaseAuth.sendPasswordResetEmail requires that the email you're sending the forgot password email to is not empty. Before calling the function check if the email is not empty.
private void beginforgotpasswd(String email)
{
if(email.isEmpty()) {
// display toast
} else {
firebaseAuth.sendPasswordResetEmail(email).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(login.this,"Email sent",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(login.this,"Failed...",Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//get and show proper error message
Toast.makeText(login.this,""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}

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

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

Firebase createUserWithEmailAndPassword task.isSuccessful()

I'm creating an Android application and am implementing the login / register functionality.
I'm at the stage where the register activity is successfully creating user entries in my Firebase application, however, I can't seem to track if the task was successful.
private void startRegister() {
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
String confirmPassword = mConfirmPassword.getText().toString();
// Check that fields are not empty
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword)) {
Toast.makeText(Register.this, "Email, password or confirm password field cannot be empty.", Toast.LENGTH_LONG).show();
} else if (!password.equals(confirmPassword)) {
Toast.makeText(Register.this, "Password and confirm password should match", Toast.LENGTH_LONG).show();
} else {
mAuth.createUserWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(Register.this, "Success", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Register.this, "Failure", Toast.LENGTH_LONG).show();
}
});
}
}
Both the if !task.isSuccessful() or else blocks ever get reached but the user is created in Firebase. Any ideas why I can't track the success/if it failed?
IN COMPARISON:
This is working in my login class.
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(Login.this, "Credentials error, user may not exist.", Toast.LENGTH_LONG).show();
}
}
});
Hard to say what's going with the current way of implementation.
Try adding a onSuccess directly
mAuth.createUserWithEmailAndPassword(email, pass).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
//done
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//display toast if registering failed
ToastRect.failed(RegisterActivity.this, getString(R.string.app_activities_error_text)
}
});
public class Register extends AppCompatActivity {
private EditText mEmailField;
private EditText mPasswordField;
private EditText mConfirmPassword;
private Button mRegisterButton;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FirebaseApp.initializeApp(this);
setContentView(R.layout.activity_register);
mEmailField = findViewById(R.id.registerEmailField);
mPasswordField = findViewById(R.id.registerPasswordField);
mConfirmPassword = findViewById(R.id.registerConfirmPassword);
mRegisterButton = findViewById(R.id.registerButton);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(Register.this, UploadActivity.class));
}
}
};
// https://stackoverflow.com/questions/10936042/how-to-open-layout-on-button-click-android
Button register = (Button) findViewById(R.id.navigate_to_login);
register.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Login.class);
startActivityForResult(myIntent, 0);
}
});
mRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startRegister();
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
private void startRegister() {
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
String confirmPassword = mConfirmPassword.getText().toString();
// Check that fields are not empty
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword)) {
Toast.makeText(Register.this, "Email, password or confirm password field cannot be empty.", Toast.LENGTH_LONG).show();
} else if (!password.equals(confirmPassword)) {
Toast.makeText(Register.this, "Password and confirm password should match", Toast.LENGTH_LONG).show();
} else {
mAuth.createUserWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(Register.this, "Success", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Register.this, "Failure", Toast.LENGTH_LONG).show();
}
});
}
}
}
To confirm the FirebaseAuth.AuthStateListener() was kicking in. This was a bad copy and paste job from the my Login class. This was stopping me handle the successful user creation.
The fix then looked like:
public class Register extends AppCompatActivity {
private EditText mEmailField;
private EditText mPasswordField;
private EditText mConfirmPassword;
private Button mRegisterButton;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FirebaseApp.initializeApp(this);
setContentView(R.layout.activity_register);
mEmailField = findViewById(R.id.registerEmailField);
mPasswordField = findViewById(R.id.registerPasswordField);
mConfirmPassword = findViewById(R.id.registerConfirmPassword);
mRegisterButton = findViewById(R.id.registerButton);
mAuth = FirebaseAuth.getInstance();
// https://stackoverflow.com/questions/10936042/how-to-open-layout-on-button-click-android
Button register = (Button) findViewById(R.id.navigate_to_login);
register.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Login.class);
startActivityForResult(myIntent, 0);
}
});
mRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startRegister();
}
});
}
#Override
protected void onStart() {
super.onStart();
}
private void startRegister() {
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
String confirmPassword = mConfirmPassword.getText().toString();
// Check that fields are not empty
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword)) {
Toast.makeText(Register.this, "Email, password or confirm password field cannot be empty.", Toast.LENGTH_LONG).show();
} else if (!password.equals(confirmPassword)) {
Toast.makeText(Register.this, "Password and confirm password should match", Toast.LENGTH_LONG).show();
} else {
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(Register.this, "Password and confirm password should match", Toast.LENGTH_LONG).show();
}
}
});
}
}
}

Cannot create PhoneAuthCredential without verificationProof?

I have followed the guideline of firebase docs to implement login into my app but there is a problem while signup, the app is crashing and the catlog showing the following erros :
Process: app, PID: 12830
java.lang.IllegalArgumentException: Cannot create PhoneAuthCredential without either verificationProof, sessionInfo, ortemprary proof.
at com.google.android.gms.common.internal.Preconditions.checkArgument(Unknown Source)
at com.google.firebase.auth.PhoneAuthCredential.<init>(Unknown Source)
at com.google.firebase.auth.PhoneAuthProvider.getCredential(Unknown Source)
at app.MainActivity.verifyPhoneNumberWithCode(MainActivity.java:132)
at app.MainActivity.onClick(MainActivity.java:110)
at android.view.View.performClick(View.java:4803)
at android.view.View$PerformClick.run(View.java:20102)
at android.os.Handler.handleCallback(Handler.java:810)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:189)
at android.app.ActivityThread.main(ActivityThread.java:5532)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
I've tried to see other code examples but they are simmiler to my code but still my app crashes with the same error.
and this is my code i wrote using the guidline of firebase documents :
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private FirebaseAuth mAuth;
private String mVerificationId;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
Button login,verify,signout;
EditText number;
EditText code;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
login = findViewById(R.id.btnlogin);
verify = findViewById(R.id.btnverify);
signout = findViewById(R.id.btnsignout);
number = findViewById(R.id.editnumber);
code = findViewById(R.id.editcode);
login.setOnClickListener(this);
verify.setOnClickListener(this);
signout.setOnClickListener(this);
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(MainActivity.this, "Error" + e.toString(), Toast.LENGTH_SHORT).show();
if (e instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(MainActivity.this, "Invalid Request " + e.toString(), Toast.LENGTH_SHORT).show();
} else if (e instanceof FirebaseTooManyRequestsException) {
Toast.makeText(MainActivity.this, "The SMS quota for the project has been exceeded " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCodeSent(String vId, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
Toast.makeText(MainActivity.this, "Code Sent" + vId, Toast.LENGTH_SHORT).show();
number.setText("");
mVerificationId = vId;
}
};
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
mAuth.signInWithCredential(phoneAuthCredential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isComplete()){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = null;
if (user != null) {
uid = user.getUid();
}
Toast.makeText(MainActivity.this, "Signed In", Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, uid, Toast.LENGTH_SHORT).show();
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(MainActivity.this, "Invalid Code", Toast.LENGTH_SHORT).show();
}
}
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnlogin: {
String phonenumber = number.getText().toString();
startPhoneNumberVerification(phonenumber);
}
case R.id.btnverify: {
String vCode = code.getText().toString();
verifyPhoneNumberWithCode(mVerificationId, vCode);
}
case R.id.btnsignout: {
mAuth.signOut();
}
}
}
private void startPhoneNumberVerification(String phoneNumber) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(phoneNumber, 60, TimeUnit.SECONDS, this, mCallbacks);
}
private void verifyPhoneNumberWithCode(String verificationId, String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithPhoneAuthCredential(credential);
}
}
The Above code is sending the otp to the given number but it crashes and cat-log shows the error mentioned above.
Please try to help me to figure out what is the error in my code rather referring to other codes.
you are getting number without country code like +91 use with country code or use
String withCountryCode = "+91"+code
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, withCountryCode);
signInWithPhoneAuthCredential(credential);

Categories

Resources