How to handle FirebaseAuth exceptions - android

I'm using the auth service from Firebase it works but I don't know how to handle the error codes of createUserWithEmailAndPassword() like auth/email-already-in-use or auth/invalid-email ,here you can see the error list https://firebase.google.com/docs/reference/js/firebase.auth.Auth#createUserWithEmailAndPassword
public void register(View target){
EditText email = (EditText) findViewById(R.id.editTextName);
EditText pass = (EditText) findViewById(R.id.editTextPass);
Log.d("email",email.getText().toString());
Log.d("pass",pass.getText().toString());
auth.createUserWithEmailAndPassword(email.getText().toString(),pass.getText().toString())
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>(){
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(RegistroActivity.this, "success",
Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(RegistroActivity.this, "fail",
Toast.LENGTH_SHORT).show();
}
}
});
}

FirebaseAuth.getInstance().createUserWithEmailAndPassword("EMAIL", "PASSWORD")
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
if (task.getException() instanceof FirebaseAuthUserCollisionException) {
// thrown if there already exists an account with the given email address
} else if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// thrown if the email address is malformed
} else if (task.getException instanceof FirebaseAuthWeakPasswordException) {
// thrown if the password is not strong enough
}
}
}
});

Related

Android Studio issue, having problem sigin up even when the password and email is correct. and am not gettin FCM token in my firebase account

I don't know if the problem is from the code. After signing up, when i try to log in, it shows "Wrong Credentials or Bad Connection! Try Again", which is the error to be called if the password is wrong or the email id is wrong.
firebaseAuth.signInWithEmailAndPassword(id,pass).addOnCompleteListener(SignInActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
String id=editID.getEditText().getText().toString().trim()+"#gmail.com";
db.collection("User").whereEqualTo("email",id).get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
User obj=new User();
for(QueryDocumentSnapshot doc:queryDocumentSnapshots)
obj=doc.toObject(User.class);
FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
#Override
public void onComplete(#NonNull com.google.android.gms.tasks.Task<String> task) {
try {
String token = task.getResult();
Log.e("DeviceToken = ",token);
}catch (Exception e){
e.printStackTrace();
}
}
});
db.document("User/"+firebaseAuth.getCurrentUser().getEmail()).update("fcmToken",SharedPref.getInstance(getApplicationContext()).getToken())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText(SignInActivity.this, "Registered for Notifications Successfully !", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(SignInActivity.this, "Registration for Notifications Failed !\nPlease Sign in Again to Retry", Toast.LENGTH_SHORT).show();
}
}
});
If a Task fails, it contains an exception with additional information in why it failed. You should log that exception:
db.document("User/"+firebaseAuth.getCurrentUser().getEmail()).update("fcmToken",SharedPref.getInstance(getApplicationContext()).getToken())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText(SignInActivity.this, "Registered for Notifications Successfully !", Toast.LENGTH_SHORT).show();
}
else
{
// 👇
Log.e("Auth", "Registration for Notifications Failed", task.getException());
Toast.makeText(SignInActivity.this, "Registration for Notifications Failed !\nPlease Sign in Again to Retry", Toast.LENGTH_SHORT).show();
}
}
});
Once you get the exception, search for the error message to see if others have dealt with the problem before.

Firebase authentication fail

I followed the steps of Firebase to create new users and I get an error, this is my method and is called by one onClickListener, what's wrong?
private void newUser(){
String finalEmail, finalPassword, repassw;
finalEmail = email.getText().toString();
finalPassword = password.getText().toString();
repassw = repassword.getText().toString();
if (finalPassword.equals(repassw)){
mAuth.createUserWithEmailAndPassword(finalEmail, finalPassword).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(SignUp.this,"Sucessfull!",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(SignUp.this,"Error!",Toast.LENGTH_SHORT).show();
}
}
});
}
else {
Toast.makeText(this,"Not the same password", Toast.LENGTH_SHORT).show();
}
}

How to add username with FirebaseAuth in android

Firebase register code is given below. When I add username as a parameter, the method does not let me do it.
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//checking if success
if(task.isSuccessful()){
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}else{
//display some message here
Toast.makeText(RegisterActivity.this,"Bir hata oldu",Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
you need to update user after creating it.
firebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(YourActivity.this, "An error occurred", Toast.LENGTH_SHORT).show();
} else {
addUserNameToUser(task.getResult().getUser());
}
}
)};
private void addUserNameToUser(User user){
String username = "username";
String email = user.getEmail();
String userId = user.getUid();
User user = new User(username, email);
firebaseDB.child("users").child(userId).setValue(user);
}
the variable firebaseDB should be created before. You can create in where you create firebaseAuth like so ;
firebaseDB = FirebaseDatabase.getInstance().getReference();
Update 1
using com.google.firebase:firebase-auth:11.6.2
public class MainActivity extends AppCompatActivity {
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.createUserWithEmailAndPassword("erginersoyy#gmail.com", "12345").addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(MainActivity.this, "An error occurred", Toast.LENGTH_SHORT).show();
} else {
addUserNameToUser(task.getResult().getUser());
}
}
});
}
private void addUserNameToUser(FirebaseUser user) {
String username = "username";
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(username)
.setPhotoUri(Uri.parse("https://example.com/jane-q-user/profile.jpg"))
.build();
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User profile updated.");
}
}
});
}
}
you can also check this link

How to delete a registered user by using firebase auth in android studio?

I have created the Register method using firebase authentication user register method.
How to delete a registered user by using firebase auth and android studio?
private void registerUser(){
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
firebaseAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>(){
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//user successfully registered and logged in
Toast.makeText(MainActivity.this, "Registered Successfully",Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
finish();
startActivity(new Intent(getApplicationContext(),ProfileActivity.class));
}else{
Toast.makeText(MainActivity.this, "Could Not Register. Please Try Again Later",Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
}
private void deleteUser(){
// TODO: Fill this method
}
You can use delete() method to remove the desired user from the Firebase. Please use this code:
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
AuthCredential authCredential = EmailAuthProvider.getCredential("user#example.com", "password1234");
firebaseUser.reauthenticate(authCredential).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
firebaseUser.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User account deleted!");
}
}
});
}
});

Check if email and password are correct Firebase

I'm currently working on an app that shows users in a listview and when you click on a user, you get to see the details.
Now you can 'add' users by filling in editText field with his or her info. Now I want that only the person himself can add his or her info. I added a editText asking for your email and an editText asking for a password. These credentials should match an account previously created in the app in Firebase. I do not seem to accomplish it.
This is my code:
String email2 = mEmailField.getText().toString();
String pw = mPassword.getText().toString();
firebaseAuth.signInWithEmailAndPassword(email2, pw).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
When the user fills in his email and password everything works, but when the incorrect password is entered, it works as well and that should not happen. What did I do wrong?
Inside OnComplete check if the Authentication was successful.
public void onComplete(#NonNull final Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getContext(), "Authentication Successful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Authentication failed.",Toast.LENGTH_SHORT).show();
}
}
mAuth.signInWithEmailAndPassword(et_LogIn_Email.getText().toString(),et_LogIn_Pasword.getText().toString())
.addOnCompleteListener((EntryActivity) requireActivity(), new OnCompleteListener<AuthResult>() {
#SuppressLint("SetTextI18n")
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText((EntryActivity) requireActivity(), "LogIn...", Toast.LENGTH_SHORT).show();
loadingDialog.stopLoading();
gotoUiPage();
} else {
Toast.makeText((EntryActivity) requireActivity(), "Error! try again...", Toast.LENGTH_SHORT).show();
tv_LogIn_warning.setText("Enter Carefully!...");
loadingDialog.stopLoading();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
tv_LogIn_warning.setText(e.getMessage());
}
});
onFailureListener provide an exception by which you handle it.

Categories

Resources