Firebase authentication fail - android

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

Related

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 separate two users in the firebase in android

In my application, I have two users--Event Member and Client--they have separate user login and registration. If a client log in he will go to the the client activity; if an event member will log in he will go to the event member activity. How will I make sure that the email is a client or an event member?
Below image shows my firebase structure:
Here is my code:
SignupClient.java
signupClient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String cemail = clie_email.getText().toString().trim();
final String cpassword = clie_password.getText().toString().trim();
String ccpassword = clie_cpassword.getText().toString().trim();
final String cfname = clie_firstname.getText().toString().trim();
final String clname = clie_lastname.getText().toString().trim();
final String cbday = clie_birthday.getText().toString().trim();
final String ccountry = clie_country.getSelectedItem().toString();
final String cmobile = clie_mobile.getText().toString().trim();
auth.createUserWithEmailAndPassword(cemail, cpassword)
.addOnCompleteListener(_5_SignupClient.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(_5_SignupClient.this, "createUserWithEmail: onComplete" + task.isSuccessful(), Toast.LENGTH_LONG).show();
if (!task.isSuccessful()){
Toast.makeText(_5_SignupClient.this, "Authentication Failed" + task.getException(),
Toast.LENGTH_LONG).show();
}
else {
AccountInfo accountInfo = new AccountInfo(cfname, clname, cemail, cpassword, cbday, ccountry, cmobile);
mDatabaseReference.child("client").push().setValue(accountInfo);
startActivity(new Intent(_5_SignupClient.this, _7_ViewClient.class));
finish();
}
}
});
}
});
LoginClient.java
loginClient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String clie_unameemail = clie_emailuname.getText().toString();
final String clie_pass = clie_password.getText().toString();
if(TextUtils.isEmpty(clie_unameemail)){
Toast.makeText(getApplicationContext(), "Field cannot be empty", Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(clie_pass)){
Toast.makeText(getApplicationContext(), "Field cannot be empty", Toast.LENGTH_LONG).show();
return;
}
auth.signInWithEmailAndPassword(clie_unameemail, clie_pass)
.addOnCompleteListener(_3_LoginClient.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
ref = FirebaseDatabase.getInstance().getReference().child("client");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
if(FirebaseAuth.getInstance().getCurrentUser().getUid().equals(snapshot.getKey())){
startActivity(new Intent(_3_LoginClient.this, _7_ViewClient.class));
}
}
// startActivity(new Intent(_3_LoginClient.this, Normal_memberActivity.class));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
// User is signed out
}
// ...
}
};
if (!task.isSuccessful()) {
// there was an error
if (clie_pass.length() < 8) {
clie_password.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(_3_LoginClient.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(_3_LoginClient.this, "Successfully Registered", Toast.LENGTH_LONG).show();
Intent intent = new Intent(_3_LoginClient.this, _7_ViewClient.class);
startActivity(intent);
finish();
}
}
});
}
});
I hope you could help me. Thank you!
On your db there should be one more field like we say it USER_TYPE. While registering the user send its USER_TYPE. suppose if you are registering a user as a CLIENT then inser db value USER_TYPE="CLIENT" and if its as an Event member registration then inser db value USER_TYPE="EVENT" and now once you logged in check its USER_TYPE and redirect him based upon his USER_TYPE

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!");
}
}
});
}
});

android firebase - displayname is not setting the display name. is this a bug?

It seems I can only find a way to update the display name of a current user, although I would like to do it while registering.
Here is the code I have been trying but it is not working, i have read about a bug in firebase that requires signing out for the display name to show but this hasnt solved my problem. Here is the code
public void btnRegistrationUser_Click(View v) {
final String email = txtEmailAddress.getText().toString();
final String password = txtPassword.getText().toString();
final String username = txtUsername.getText().toString();
final ProgressDialog progressDialog = ProgressDialog.show(RegistrationActivity.this, "Please wait...", "Processing...", true);
(firebaseAuth.createUserWithEmailAndPassword(email,password ))
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (task.isSuccessful()) {
//Sign in the user here
signin(email,password,username);
}
else
{
Log.e("ERROR", task.getException().toString());
Toast.makeText(RegistrationActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
private void signin(String email, String password, final String username) {
firebaseAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//New Account is signed in and now the Current User
FirebaseUser user = firebaseAuth.getInstance().getCurrentUser();
Toast.makeText(RegistrationActivity.this, "curr user is "+user.getEmail(), Toast.LENGTH_LONG).show();
Toast.makeText(RegistrationActivity.this, "passed in username is "+username, Toast.LENGTH_LONG).show();
firebaseAuth.getInstance().signOut();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(username)
.build();
// Toast.makeText(RegistrationActivity.this, "Registration successful", Toast.LENGTH_LONG).show();
Toast.makeText(RegistrationActivity.this, "curr display name is "+user.getDisplayName(), Toast.LENGTH_LONG).show();
Intent i = new Intent(RegistrationActivity.this, LoginActivity.class);
startActivity(i);
}
}
});
}
}
Thanks
Maybe you could try to login the user since the account registration is successful. That way the current user would be the currently registered one.
public void btnRegistrationUser_Click(View v) {
final String email = txtEmailAddress.getText().toString();
final String password = txtPassword.getText().toString();
final String username = txtUsername.getText().toString();
final ProgressDialog progressDialog = ProgressDialog.show(RegistrationActivity.this, "Please wait...", "Processing...", true);
(firebaseAuth.createUserWithEmailAndPassword(email,password ))
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (task.isSuccessful()) {
//Sign in the user here
signin(email,password,username);
}
else
{
Log.e("ERROR", task.getException().toString());
Toast.makeText(RegistrationActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
private void signin(String email, String password, final String username) {
firebaseAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//New Account is signed in and now the Current User
FirebaseUser user = firebaseAuth.getInstance().getCurrentUser();
Toast.makeText(RegistrationActivity.this, "curr user is "+user.getEmail(), Toast.LENGTH_LONG).show();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(username)
.build();
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(RegistrationActivity.this, "curr display name is "+user.getDisplayName(), Toast.LENGTH_LONG).show();
}
}
});
Intent i = new Intent(RegistrationActivity.this, LoginActivity.class);
startActivity(i);
}
}
});
You also forgot the user by calling the updateProfile() method.
Check this out for more info: https://firebase.google.com/docs/auth/android/manage-users

How to handle FirebaseAuth exceptions

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

Categories

Resources