I'm trying to develop an android app with android studio 2.3.3 and genymotion 2.10.0
I'm using toast msg to show the firebase connection result but it's not displayed despite there are no errors.
here is my code
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithEmail:failed", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed !",
Toast.LENGTH_SHORT).show();
setContentView(R.layout.failure);
finish();
}
else{
setContentView(R.layout.success);
Intent settings = new Intent(LoginActivity.this,SettingsActivity.class);
startActivity(settings);
finish();
}
}
});
It doesn't show because you finish the Activity after the toast
you can change your ActivityContext to applicationContext
Toast.makeText(getApplicationContext(), "Authentication failed!" , Toast.LENGTH_SHORT).show();
Related
I am trying to implement a basic android authentication system with Firebase. The following is my code:
Toast.makeText(MainActivity.this, "BEFORE ON-COMPLETE", Toast.LENGTH_SHORT).show(); //this shows up
mAuth.signInWithEmailAndPassword(emailInputted, passInputted).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(MainActivity.this, "in OnComplete", Toast.LENGTH_SHORT).show(); //this does not show up
if(task.isSuccessful()){
Intent i = new Intent(MainActivity.this, Dashboard.class);
i.putExtra("EMAIL", emailInputted);
Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_SHORT).show();
startActivity(i);
} else {
Toast.makeText(MainActivity.this, "Please check email/password", Toast.LENGTH_SHORT).show();
}
}
});
Toast.makeText(MainActivity.this, "after OnComplete", Toast.LENGTH_SHORT).show(); //this shows up
I took this code from the official Firebase docs, but for some reason it is not working. The onComplete method is not being called for some reason. I can see the "before on-Complete" and "after on-complete" toasts, but not the "in OnComplete" one. I have added the users in my authentication table in the firebase console, and I am positive that I am entering the correct password.
After using the debugger, I saw that my code just skips over the onComplete() method, and does not even get to the isSuccessful() method. How do I fix this?
Thanks in advance!
Follow this, I hop you will get your answer.
lBut = findViewById(R.id.log_btn);
lBut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String a = usrn.getText().toString().trim();
String b = pswd.getText().toString().trim();
if (TextUtils.isEmpty(a) && TextUtils.isEmpty(b)) {
usrn.setError("Empty Email !!");
pswd.setError("Empty Password !!");
lBut.setClickable(false);
} else {
lBut.setClickable(true);
mAuth.signInWithEmailAndPassword(a, b).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#SuppressLint("ShowToast")
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Successfully Login!!", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), HomeP.class);
ProgressBar prb = findViewById(R.id.progressBar);
prb.setVisibility(View.VISIBLE);
startActivity(i);
finish();
} else
Toast.makeText(getApplicationContext(), "Check Error And Try Again!!", Toast.LENGTH_SHORT).show();
}
});
}
}
});
This is the Event on the Login Button, you have more doubt then reply me.
So it fixed itself after I restarted my computer. No code changes. Maybe Android Studio was being wacky.
Firstly i want to check the password and email is true with fireauth. If the password is false not same with fireauth, that will popup toast.
firebaseAuth.signInWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if(task.isSuccessful()){
finish();
if(!password.equals()){
}
userVerified();
}else{
Toast.makeText(Signin.this, "Your account not registered",Toast.LENGTH_LONG).show();
startActivity(new Intent(getApplicationContext(),Signup.class));
}
}
});
}
i stuck on password.equals. i don't know how to match with fireauth.
task.getException() gives you the exact error of the sign in failure, so in the else part in your Toast message you can print the exception message. Do let me know if this helps.
I am trying to implement google sign-in feature in my app. I have followed this documentation, problem is - if I use previously used google account, it is not showing an error like "the e-mail is already registered in this app". As a result, previously stored data with the account are deleted & the google account is registered again. Here is my code :
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
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");
FirebaseUser user = mAuth.getCurrentUser();
int coins = 100;
String name, email;
name = user.getDisplayName();
email = user.getEmail();
//updateUI(user);
storeUserCredentials(name, email, coins);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(SignUpActivity.this, "Error : " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
public void storeUserCredentials(String name, String email, int coins){
progressBar.setVisibility(View.VISIBLE);
User user = new User(name, email, coins);
mDatabase.getReference("Users")
.child(mAuth.getCurrentUser().getUid())
.setValue(user)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()){
Toast.makeText(SignUpActivity.this, "Registration Successful!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(SignUpActivity.this, MainActivity.class));
finish();
} else {
if (task.getException() instanceof FirebaseAuthUserCollisionException){
Toast.makeText(SignUpActivity.this, "The email is already used", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(SignUpActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
});
}
What is wrong with my code, please explain.
When you call signInWithCredential the SDK returns a task that successfully completes when the user is signed in. Since you call storeUserCredentials on that condition, it will get called each time the user is signed in. This is actually a quite normal flow.
If you want to detect if this account is new to Firebase Authentication, you can check the creation time of the user. See Firebase Auth, how to know new user signed up, rather than existing user sign in?
If you want to detect whether you've already seen the user before, you'll want to check in the database before calling storeUserCredentials. But what you now have is a pretty idiomatic flow, since it for example ensures you store the up-to-date display name each time you ask the user to sign in.
This is the error message I get everytime I register a new user then log in. Above is the error message and below is my code. Please help me, thank you in advance! Just trying to complete my first app.
//initialize the button for log in
Button btnLogin= (Button) findViewById(R.id.btn_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: attempting to log in.");
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
if (isStringNull(email) && isStringNull(password)){
Toast.makeText(mContext, "You must fill out all the fields", Toast.LENGTH_SHORT).show();
}else{
mProgressBar.setVisibility(View.VISIBLE);
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful());
FirebaseUser user = mAuth.getCurrentUser();
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithEmail:failed", task.getException());
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_SHORT).show();
mProgressBar.setVisibility(View.GONE);
}else{
try{
if (user.isEmailVerified()){
Log.d(TAG, "onComplete: success. Email is verified.");
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(intent);
}else{
Toast.makeText(mContext, "Email is not verified \n check your email inbox.", Toast.LENGTH_SHORT).show();
mProgressBar.setVisibility(View.GONE);
mAuth.signOut();
}
}catch (NullPointerException e){
Log.e(TAG, "onComplete: NullPointerException: " + e.getMessage() );
I had a similar problem. Here's how I solved it :
My entire code was correct, but Firebase requires your password to be of minimum 8 characters and should include at least one numeric value. Try setting a password which matches the above guidelines.
I'm trying to create users table in Firebase realtime database.However, everytime user re-logins his previously entered data is being removed or overwritten.Couldnt understand how should I change it.
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(RegisterActivity.this,"Registration Is Succesfull",Toast.LENGTH_LONG).show();
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user=mAuth.getCurrentUser();
final String databaseUserName=user.getDisplayName();
String name=mAuth.getCurrentUser().getDisplayName();
DatabaseReference myRootRef = FirebaseDatabase.getInstance().getReference().child("Users");
DatabaseReference userNameRef = myRootRef.child(databaseUserName);
//after that user is redirected to the main account activity.
Intent accountIntent = new Intent(RegisterActivity.this,UserAccountActivity.class);
accountIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(accountIntent);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(RegisterActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
// if signing up task is unsuccesfull we do make a error indication pretty much.
FirebaseAuthException e = (FirebaseAuthException )task.getException();
Toast.makeText(RegisterActivity.this, "Failed Registration: "+e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("LoginActivity", "Failed Registration", e);
}
}
});
}
So once I run the code, for the very first time it works perfectly fine and say I edit&add additional user info but once the user logs out and re-enters, everything is cleared out and node is again created.
Here you are saving the data in the database:
DatabaseReference myRootRef = FirebaseDatabase.getInstance().getReference().child("Users");
DatabaseReference userNameRef = myRootRef.child(databaseUserName);
Now on the second time, the data is not getting deleted or cleared, it cannot be deleted magically, the data is getting overridden. All you need to do is add a push() that will create a random id for each log in.
So like this:
DatabaseReference myRootRef = FirebaseDatabase.getInstance().getReference().child("Users").push();
DatabaseReference userNameRef = myRootRef.child(databaseUserName)
Edit:
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(Activity_name_here.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(getApplicationContext(), "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
Here is the working version of the source code. You can use the very same code for facebook login as well. This code simply prevents user from overwriting when logging in again.
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(SignInActivity.this,"Registration Is Succesfull",Toast.LENGTH_LONG).show();
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
//getting current users account
FirebaseUser user=mAuth.getCurrentUser();
//getting the display name of the current user to store them in our real time database
final String databaseUserName=user.getDisplayName();
//creating a child called users
final DatabaseReference myRootRef = FirebaseDatabase.getInstance().getReference().child("Users");
//here we make a control such that, if logged in user is exist in the realtime database
//if not exists, then we save them , if exists we continue with the else statement and break it.
myRootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(databaseUserName)){
DatabaseReference userNameRef = myRootRef.child(databaseUserName);
//value is also set to user display name however it doenst have to be so
userNameRef.setValue(databaseUserName);
} else{
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//after that user is redirected to the main account activity.
Intent accountIntent = new Intent(SignInActivity.this,UserAccountActivity.class);
accountIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(accountIntent);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(SignInActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
// if signing up task is unsuccesfull we do make a error indication pretty much.
FirebaseAuthException e = (FirebaseAuthException )task.getException();
Toast.makeText(SignInActivity.this, "Failed Registration: "+e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("LoginActivity", "Failed Registration", e);
}
}
});
}