Firebase not firing a success or unsuccess - java

I've followed the instructions exactly, in fact, I even used the code from the Firebase helper in android studio. My issue is as such, nor login or failure to login is occurring with my code! What am I missing?
public void toSubscribe(View v) {
Log.d("OK", "this part first");
String strUsername, strPassword;
strUsername = ((EditText) findViewById(R.id.username)).getText().toString();
strPassword = ((EditText) findViewById(R.id.password)).getText().toString();
if (strUsername.matches("")) {
Toast.makeText(MainActivity.this, "You did not enter a username.", Toast.LENGTH_SHORT).show();
return;
}
if (strPassword.matches("")) {
Toast.makeText(MainActivity.this, "You did not enter a password.", Toast.LENGTH_SHORT).show();
return;
}
mAuth.signInWithEmailAndPassword(strUsername, strPassword)
.addOnCompleteListener(MainActivity.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", task.getException());
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
Not much else to say... I tried using a new JSON file and it still doesn't work. I've Googled tons of stuff but nothing really worked.

please check the following:
1-you install and add Gson file correctly from firebase console
2- you enable firebase authentication from firebase console
3- you mAuth initialized correctly

Related

Why is firebase failing to create a new user?

I am trying to make it so that the user can enter in various importation and that firebase can enter this information into the Runtime DB. However, when I press the button that makes the code below happen, it results in the progress bar loading forever. I tried throwing in the log to try to catch some exception, but no exceptions came up. On the firebase console, the user was not created in the authentication and nothing was added to the RunTime DB. I am not sure what is causing this to happen, and I would appreciate any and all help.
Code:
User user = new User(fullName, email, bio, username,location,realstatus,profilePic);
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference root = db.getReference().child("Users");
progressBar.setVisibility(ViewStub.VISIBLE);
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Toast.makeText(Register.this, "Create User Succeeded", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(Register.this, "Failed to Authenticate :( ", Toast.LENGTH_SHORT).show();
}
}
});
root.push().setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()) {
progressBar.setVisibility(ViewStub.GONE);
Toast.makeText(Register.this, "Data Saved", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(Register.this, "Failed to Register User :( ", Toast.LENGTH_SHORT).show();
Log.e("Create user", "Failed to create user", task.getException());
}
}
});
Error:
com.google.firebase.FireBaseException:
An internal error has occured. [ socket failed EPERM:(Operation not permitted) ]
Add a completion listener to the createUser so you can know why it isn't working.
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, task -> {
binding.progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
//get the error here with task.toString();
} else {
save your database data here
}
});
That will at least help you get to the bottom of why it is failing. Also make sure you have
enabled email auth in firebase console
Have properly set up your app, the SHA-1s, the google-services json and all

i can't resolve the errors symbol from firebase authentification

i try to do a firebase connection with email and password, but i ah two symbol errors when i try to build.
the first one come from the AnotherActivity.class i don't know how to resolve it
public void updateUI(FirebaseUser account){
if(account != null){
Toast.makeText(this,"U Signed In successfully",Toast.LENGTH_LONG).show();
startActivity(new Intent(this,AnotherActivity.class));
}else {
Toast.makeText(this,"U Didnt signed in",Toast.LENGTH_LONG).show();
}
}
and the second come from EmailPasswordActivity.this
private void callsignin(String email, String password) {
mAuth.signInWithEmailAndPassword(email, password)
.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("success", "signInWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w("failed", "signInWithEmail:failure", task.getException());
Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
}
});
}
i think i need to write something in the manifest file but i don't what. Thank you for your attention and I hope you can help me
errors :
settings :
import :
It seems that the import statements are missing for AnotherActivity and EmailPasswordActivity.
At the top of your file, just below the package line, add these lines:
import <package_name>.AnotherActivity
import <package_name>.EmailPasswordActivity
For Android Studio shortcuts, Please refer to this post on how to use import in Android.
https://stackoverflow.com/a/30731266/9636037

How to check if user is already signed in via gmail or google account?

if(!em.isEmpty() || !pass.isEmpty()) {
mfirebaseAuth.signInWithEmailAndPassword(em, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Logged in successfully", Toast.LENGTH_SHORT).show();
} else {
String errorCode = ((FirebaseAuthException) task.getException()).getErrorCode();
switch (errorCode) {
case "ERROR_INVALID_EMAIL":
Toast.makeText(MainLoginActivity.this, "The email address is badly formatted.", Toast.LENGTH_LONG).show();
email.setError("The email address is badly formatted.");
email.requestFocus();
break;
case "ERROR_USER_MISMATCH":
Toast.makeText(MainLoginActivity.this, "The supplied credentials do not correspond to the previously signed in user.", Toast.LENGTH_LONG).show();
break;
case "ERROR_ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL":
Toast.makeText(MainLoginActivity.this, "An account already exists with the same email address but different sign-in credentials. Sign in using associated email address.", Toast.LENGTH_LONG).show();
break;
case "ERROR_EMAIL_ALREADY_IN_USE":
Toast.makeText(MainLoginActivity.this, "The email address is already in use by another account.", Toast.LENGTH_LONG).show();
email.requestFocus();
break;
case "ERROR_CREDENTIAL_ALREADY_IN_USE":
Toast.makeText(MainLoginActivity.this, "This credential is already associated with a different user account.", Toast.LENGTH_LONG).show();
break;
case "ERROR_USER_DISABLED":
Toast.makeText(MainLoginActivity.this, "The user account has been disabled by an administrator.", Toast.LENGTH_LONG).show();
break;
case "ERROR_INVALID_USER_TOKEN":
Toast.makeText(MainLoginActivity.this, "The user\\'s credential is no longer valid. The user must sign in again.", Toast.LENGTH_LONG).show();
break;
case "ERROR_WRONG_PASSWORD":
Toast.makeText(MainLoginActivity.this, "The password is invalid or the user does not have a password.", Toast.LENGTH_LONG).show();
password.setError("password is incorrect ");
password.requestFocus();
password.setText("");
break;
default:
Toast.makeText(getApplicationContext(), "Error! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
});
}
The Problem I am facing is:
The user first signup using 'signup with email'. After that the user signup with a Google account(With the same email).
Now after that when the user tries to login via email and password. I get the error that the password is incorrect, I know this happens because sign up with email details has been overwritten by Google account details.
I want to show the error "The email is linked with google account. Please login via google account".
You should use AuthCredential and isNewUser Here is the example
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d("TAG", "signInWithCredential:success" + 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) {
boolean isNewUser = task.getResult().getAdditionalUserInfo().isNewUser();
if (isNewUser) {
Log.d(TAG, "Is New User!");
FirebaseUser user = mAuth.getCurrentUser();
//do something
//You can call register class or function here
} else {
Log.d(TAG, "Is Old User!");
//Do something else
}
}
});
}
To know if a user is signed in with Google or email and password, please use the following code:
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
List<? extends UserInfo> userInfoList = firebaseUser.getProviderData();
for (UserInfo userInfo : userInfoList) {
String providerId = userInfo.getProviderId();
if (providerId.equals(GoogleAuthProvider.PROVIDER_ID)) {
//Do stuff
} else if (providerId.equals("password")) {
//Do other stuff
}
}
So you can take some action according to the way the user is signed in.

Mobile OTP Verification without signing in using Firebase Phone Auth

I am currently making an android app where I need to verify if the user is entering correct mobile number using the OTP.
The user is already signed in the application using his email and password.
Now I need to verify the mobile number the user enters without using the signInWithCrendntial() method of firebase phone auth.
How do i go about it ?
My mCallbacks is
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
Toast.makeText(getApplicationContext(), "Verification Complete", Toast.LENGTH_SHORT).show();
showMessage("Success!!","OTP verified!" + credential);
cred = credential;
//btn_add_guest.setEnabled(true);
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(getApplicationContext(), "Verification Failed", Toast.LENGTH_SHORT).show();
Log.i(TAG,"Error is "+e.getMessage());
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
Toast.makeText(getApplicationContext(), "Code Sent", Toast.LENGTH_SHORT).show();
mVerificationId = verificationId;
mResendToken = token;
Log.i(TAG,"VERFICATION ID IS"+mVerificationId);
Log.i(TAG,"RESEND TOKEN"+mResendToken);
btn_add_guest.setEnabled(false);
}
};
I m calling this method on button Pressed where put_otp is textView where user enters the OTP.
verifyPhoneNumberWithCode(mVerificationId,put_otp.getText().toString());
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, put_otp.getText().toString());
Log.i(TAG,credential.getProvider());
private void verifyPhoneNumberWithCode(String verificationId, String code) {
Log.i(TAG,"RESEND TOKEN IN METHOD IS"+mResendToken); if(code.equals(mResendToken)&&verificationId.equals(mVerificationId)){
Toast.makeText(AddGuestActivity.this, "Verification Success", Toast.LENGTH_SHORT).show();
btn_add_guest.setEnabled(true);
}
else
Toast.makeText(this,"Please provide correct OTP",Toast.LENGTH_SHORT).show();
}
You can link an email/pass account with a phone account https://firebase.google.com/docs/auth/android/account-linking?authuser=0

Firebase reflect changes directly from database?

In my Firebase application I created a fragment that allows users to update their information like namn & email and so far all is going well, however my issue is after the user have updated the information - the changes are not visible untill next relaunch of the application.
How can I reflect the changes directly from the databse without promoting the User to relaunch the app?
I have created a Method called restart(); that will like the name says says restart the application - But still the changes are not being reflected!
/**
* Update Name Only
*/
private void updateDisplayNameOnly() {
showProgress();
AuthCredential credential = EmailAuthProvider
.getCredential(FirebaseAuth.getInstance().getCurrentUser().getEmail(), mConfirm.getText().toString());
FirebaseAuth.getInstance().getCurrentUser().reauthenticate(credential)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setDisplayName(mName.getText().toString())
//.setPhotoUri(Uri.parse("https://avatarfiles.alphacoders.com/862/86285.jpg"))
.build();
user.updateProfile(profileUpdate);
Log.d(TAG, "onComplete: User Profile updated");
Toast.makeText(getActivity(), "Name is updated", Toast.LENGTH_SHORT).show();
restartApp();
} else {
Toast.makeText(getActivity(), "Name was not updated", Toast.LENGTH_SHORT).show();
}
hideProgress();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
hideProgress();
Toast.makeText(getActivity(), "You have entered wrong password", Toast.LENGTH_SHORT).show();
}
});
}
Restart Method
public void restartApp() {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
Firebase has a listener onDataChange(), so when you query data from firebase, make sure you implement that, see doc. If you want to reflect the change, implement it in this method (like resetting the text fields). There is no need for a restart method.
Update profile call is asynchronous, and its results are not available immediately, so for some time you'll still observe "obsolete" data.
When you call updateProfile, you get a task as a result. You can subscribe on completion of this task, and if it's completed successfully, then you will be able to get updated data from user instance. E.g.:
final FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
Log.i("MyActivity", "before updateProfile: username=" + currentUser.getDisplayName());
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setDisplayName("UPDATED_NAME")
.build();
final Task<Void> task = currentUser.updateProfile(profileUpdate);
Log.i("MyActivity", "after updateProfile: username=" + currentUser.getDisplayName());
task.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.i("MyActivity", "onComplete: username=" + currentUser.getDisplayName());
}
});
And here is an output:
I/MyActivity: before updateProfile: username=old name
I/MyActivity: after updateProfile: username=old name
I/MyActivity: onComplete: username=UPDATED_NAME
Also there is a method user.reload(), which force reload user data from Firebase server. This is useful when your client user cache is obsolete for some reason. It is also an asynchronous method, which gives you Task and you need to subscribe on its completion.

Categories