Cannot create PhoneAuthCredential without verificationProof? - java

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

Related

How to solve this this error. com.google.android.gms.tasks.task executors$zza cannot be cast to android.app.activity. I am new at Java & Android app

I want to verify user through phone number verification OTP code, now I am unable to fix this issue. I am new in android App development. I have connected Firebase with android studio, that's all fine except this error.
Logcat message error:
Caused by: java.lang.ClassCastException: com.google.android.gms.tasks.TaskExecutors$zza cannot be cast to android.app.Activity
at com.saqib.onlinefirregistration.VerifyOTP.sendVerificationCodeToUser(VerifyOTP.java:55)
at com.saqib.onlinefirregistration.VerifyOTP.onCreate(VerifyOTP.java:48)
VerifyOTP.java:
public class VerifyOTP extends AppCompatActivity {
//Variable
PinView pinForUser;
String codeBySystem;
Button verifyButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.verify_otp);
pinForUser = findViewById(R.id.pin_view);
verifyButton = findViewById(R.id.verify_btn);
String _PhoneNo = getIntent().getStringExtra("phoneNo");
sendVerificationCodeToUser(_PhoneNo);
}
private void sendVerificationCodeToUser(String phoneNo) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNo, // Phone No to verify
60, //timeout duration
TimeUnit.SECONDS, //Time unit
(Activity) TaskExecutors.MAIN_THREAD,
mCallback);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallback
= new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeAutoRetrievalTimeOut(#NonNull String s) {
super.onCodeAutoRetrievalTimeOut(s);
codeBySystem =s;
}
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code!=null){
pinForUser.setText(code);
verifyCode(code);
}
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(VerifyOTP.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
};
private void verifyCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codeBySystem,code);
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(VerifyOTP.this, "Verification Completed", Toast.LENGTH_SHORT).show();
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(VerifyOTP.this, "Verification Not Completed! Try Again", Toast.LENGTH_SHORT).show();
}
}
}
});
}
private void signInUsingCredential(PhoneAuthCredential credential) {
}
public void callNextScreenOTP( View view) {
String code = pinForUser.getText().toString();
if (!code.isEmpty()) {
verifyCode(code);
}
}
};
How can I fix this issue? I have no idea about it, I did search for the same question but failed to find on Google, or stack overflow.
I want to verify user through phone number verification OTP code, now I am unable to fix this issue. I am new in android App development. I have connected Firebase with android studio, that's all fine except this error.
(Activity) TaskExecutors.MAIN_THREAD line is wrong. It's clear from the error message that the cast cannot be made.
Since you're in activity, just this should do it in this place.
Just Replace: (Activity) TaskExecutors.MAIN_THREAD,
With: this,

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

authentication problem in fire base using android studio

I am working on a project which required firebase utilities so I did all those things required but my authentication is not taking place and thereby my data is not being uploaded in the firestore. I have tried many things and found that during the time of execution my onComplete listener is calling failure and thus a toast is popped authentication failure so I think the main problem lies in the onComplete listener but I couldn't fix it. My code is as follows-
*
private TextView username;
private TextView password;
private AutoCompleteTextView email;
private ProgressBar progress_bar;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener authStateListener;
private FirebaseUser currentUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = findViewById(R.id.username_account);
password = findViewById(R.id.password_account);
email = findViewById(R.id.email_account);
Button create_account = findViewById(R.id.create_acct_button);
progress_bar = findViewById(R.id.create_acct_progress);
firebaseAuth = FirebaseAuth.getInstance();
create_account.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!TextUtils.isEmpty(email.getText().toString())
&& !TextUtils.isEmpty(password.getText().toString())
&& !TextUtils.isEmpty(username.getText().toString())) {
String Email = email.getText().toString().trim();
String Password = password.getText().toString().trim();
String Username = username.getText().toString().trim();
createUserEmailAccount(Email, Password, Username);
} else {
Toast.makeText(CreateAccountActivity.this,
"Empty Fields Not Allowed",
Toast.LENGTH_LONG)
.show();
}
}
});
}
private void createUserEmailAccount(String email, String password, final String username) {
if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password) && !TextUtils.isEmpty(username)) {
progress_bar.setVisibility((View.VISIBLE));
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener( CreateAccountActivity.this,new OnCompleteListener<AuthResult>() {
#Override
public void onComplete( #NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Map<String, Object> userobj = new HashMap<>();
userobj.put("userId", "currentuserId");
userobj.put("username", username);
db.collection("journal")
.add(userobj)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Log.d(TAG, "DocumentSnapshot successfully written!");
progress_bar.setVisibility(View.INVISIBLE);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});
} else {
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(CreateAccountActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
progress_bar.setVisibility(View.INVISIBLE);
}
}
});
}
}
}*

firebase phone number authentication getting null reference

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.

Firebase authentication: signInWithEmailAndPassword method dont respond at all

I am getting problem in authentication in firebase through android app. everything is fine with code and connections. But I still don't get authenticated. I have done all the requisites like
Have enabled email/password sign in methods in firebase
Added all the required dependencies in build.gradle
checked with changing the rules (user) to null and ! null.
connections is done successfully
the problem is inside the signInWithEmialAndPassword method, neither the if nor else statement gets executed. Why is this so? I have searched a lot but all in vain. I am using emulator NEXUS 5X API 26 not actual device.
Here is the code..
package com.example.abid.fireauthapp;
import java.net.PasswordAuthentication;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
// ..
private EditText mEmailField;
private EditText mPasswordField;
private Button mLoginButton;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
// private DatabaseReference rootRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEmailField = (EditText) findViewById(R.id.emailField);
mPasswordField = (EditText) findViewById(R.id.passwordField);
mLoginButton = (Button) findViewById(R.id.loginButton);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
//show a welcome messgage and start a new activity
Toast.makeText(MainActivity.this, "Welcome", Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this,Main2Activity.class));
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
mLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StartSignIn();
}
});
}
#Override
public void onStart() {
super.onStart();
if (mAuthListener == null) {
mAuth.addAuthStateListener(mAuthListener);
}
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void StartSignIn() {
String email = mEmailField.getText().toString();
String pass = mPasswordField.getText().toString();
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(pass)){
Toast.makeText(MainActivity.this, "Fields are empty...", Toast.LENGTH_LONG).show();
}
else {
mAuth.signInWithEmailAndPassword(email, pass)
.addOnCompleteListener(this,new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task task) {
Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful());
FirebaseUser user = mAuth.getCurrentUser();
Toast.makeText(MainActivity.this, "You are sign in..", Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this,Main2Activity.class));
//These Both if and else statement dont get executed... Why ??
if (user == null) {
Log.w(TAG, "signInWithEmail:failed", task.getException());
Toast.makeText(MainActivity.this, "Error Occured",
Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Signed In successfully..", Toast.LENGTH_LONG).show();
}
// ...
}
});
}
}
}
Change your code like this.
...
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, "signInWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
Toast.makeText(MainActivity.this, "You are sign in..", Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this,Main2Activity.class));
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithEmail:failure", task.getException());
Toast.makeText(MainActivity, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
What happens?

Categories

Resources