Task.isSuccessful() is false and unable to add any user - android

FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseAuth mAuth;
EditText name, email, password;
Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
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("########", "onAuthStateChanged:signed_in:" + user.getUid());
}
else{
// User is signed out
Log.d("########", "onAuthStateChanged:signed_out");
}
}
};
name = (EditText) findViewById(R.id.input_name);
email = (EditText) findViewById(R.id.input_email);
password = (EditText) findViewById(R.id.input_password);
submit = (Button) findViewById(R.id.btn_signup);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.createUserWithEmailAndPassword(email.getText().toString(), password.getText().toString()).addOnCompleteListener(SignUp.this, new OnCompleteListener < AuthResult > () {
#Override
public void onComplete(#NonNull Task < AuthResult > task) {
Log.d("###########", "signInWithEmail:onComplete:" + task.isSuccessful());
}
});
The Task.isSuccessful() always returns false and I am not able to add any user.
I have enabled email authentication on Firebase and am able to add users from the forge itself, i am left with no way to debug and figure out where the issue is.
All other settings like adding dependencies and copying the configuration file obtained from Firebase into the app directory have been done. Please help.

I encountered the same problem, and decided to create a user from the firebase console. Then the error displayed in the image came up. The password is required to be at least 6 characters long. When signing up a new user ensure that the length of password is at least six and it should work.

I attached addOnFailureListener() and it abused:
The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.
private void register(final String user, String email,final String password) {
auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
FirebaseUser firebaseUserLcl = auth.getCurrentUser();
String userIdLcl = firebaseUserLcl.getUid();
l.a("userIdLcl="+userIdLcl);
DatabaseReference referenceLcl = FirebaseDatabase.getInstance().getReference("Users").child(userIdLcl);
HashMap<String, String> mapLcl = new HashMap();
mapLcl.put("id", userIdLcl);
mapLcl.put("email", email);
mapLcl.put("password", password);
mapLcl.put("ImageURL", "default");
referenceLcl.setValue(mapLcl).addOnCompleteListener(taskPrm -> {
if (taskPrm.isSuccessful()) {
Intent intentLcl = new Intent(RegisterActivity.this, MainActivity.class);
intentLcl.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intentLcl);
finish();
}else {
Toast.makeText(RegisterActivity.this, "Signing failed,", Toast.LENGTH_LONG).show();
}
});
} else {
// l.a(task.getException().getCause());
Toast.makeText(RegisterActivity.this, "You cannot register with this email or password", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener( e->
l.a(e.getMessage()) //logging
);
}

Related

Firebase doesn't register new users

I have a problem, I can't register in my chat app. It shows me that "You can't register". I don't know where is the problem. I set read and write to true in my database but it still not working. I use the last versions of Firebase. I haven't problems with the internet and connected firebase to my project successfully.
This is my register activity
MaterialEditText username, email, password;
Button btn_register;
FirebaseAuth auth;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Регистрация");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
username = findViewById(R.id.username);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
btn_register = findViewById(R.id.btn_register);
auth = FirebaseAuth.getInstance();
btn_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt_username = username.getText().toString();
String txt_email = email.getText().toString();
String txt_password = password.getText().toString();
if (TextUtils.isEmpty(txt_username) || TextUtils.isEmpty(txt_email) || TextUtils.isEmpty(txt_password)) {
Toast.makeText(RegisterActivity.this, "Write more", Toast.LENGTH_SHORT).show();
} else if (txt_password.length() < 6 ){
Toast.makeText(RegisterActivity.this, "Password too short ", Toast.LENGTH_SHORT).show();
} else {
register(txt_username, txt_email, txt_password);
}
}
});
}
private void register(final String username, String email, String password){
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
FirebaseUser firebaseUser= auth.getCurrentUser();
assert firebaseUser !=null;
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
HashMap<String, String> HashMap = new HashMap<>();
HashMap.put("id", userid);
HashMap.put("username", username);
HashMap.put("imageURL", "default");
reference.setValue(HashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
});
}else {
Toast.makeText(RegisterActivity.this, "You cant register", Toast.LENGTH_SHORT).show();
}
}
});
}
}
When initializing your FirebaseDatabase reference, the item node with the provided user id does not exist yet in your database thus the reference is null
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
Instead, initialize the reference to the Users node
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users");
Then when saving the user's data you can save to their userId:
reference.child(userid).setValue(HashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
...
});
in manifest file allow internet permission. if you continue this err create failure listener and print failure code
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();

how to change firebase user in andorid [duplicate]

This question already has answers here:
Firebase kicks out current user
(19 answers)
Closed 3 years ago.
im devlop an app that has group admin, this group admin can join user by sign them with firebase, and after the admin sign them i want the app will sign back to the admin(the app could have multiple admin- one for each group),
i tried to save the currfirebase user and then switch back but when firebaseauth is change it change automaticlly the pervous user, i even make him final but it didt help
private final FirebaseUser currUser = currUserauth.getCurrentUser();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_contact);
db = FirebaseFirestore.getInstance();
Button addContactBtn = findViewById(R.id.add_contact_btn);
progressBar = findViewById(R.id.add_content_progressbar);
userEmailEt = findViewById(R.id.et_email);
passwordEt = findViewById(R.id.et_password);
confirmBtnEt = findViewById(R.id.confirmBtn);
nameEt = findViewById(R.id.add_contact_name_et);
addContactBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addNewContact();
}
});
}
private void addNewContact() {
progressBar.setVisibility(View.VISIBLE);
final String email = userEmailEt.getText().toString();
String password = passwordEt.getText().toString().trim();
final String name = nameEt.getText().toString();
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches() || email.equals("")) {
userEmailEt.setError("Email is not valid");
} else if (TextUtils.isEmpty(password)) {
passwordEt.setError("password is not valid");
} else if(TextUtils.isEmpty(name)){
nameEt.setError("נא למלא שם");
}else {
mAuth.createUserWithEmailAndPassword(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
FirebaseUser firebaseUser = mAuth.getCurrentUser();
Toast.makeText(getApplicationContext(), "User created successfully", Toast.LENGTH_SHORT).show();
update();
progressBar.setVisibility(View.GONE);
mAuth.signOut();
mAuth.updateCurrentUser(currUser).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
mAuth.getCurrentUser().reload().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Intent intent = new Intent(getApplicationContext(), ContactActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
System.out.println("From addContactActivity: " + mAuth.getCurrentUser().getEmail());
startActivity(intent);
finish();
}
});
User accounts can't create other user accounts in Firebase Authentication on the frontend. Also, only one user can be signed in at a time.
What you're trying to do is best suited to run on a backend you control, using the Firebase Admin SDK to create the user accounts.

How to Login in Android application where database is maintaining in Firebase?

I have created an app with the database maintaining in Firebase. I have completed the user registration part and here is the coding I used,
if(edtUsrNameS.length() >0 && edtPassS.length() >0 &&edtEmailS.length() >0) {
strUsrS = edtUsrNameS.getText().toString().trim();
strPassS = edtPassS.getText().toString().trim();
strEmailS = edtEmailS.getText().toString().trim();
if(Constant.isValidEmail(strEmailS)){
edtEmailS.setError(null);
Map<String, String> parameters = new HashMap<>();
parameters.put(Constant.TAG_USER, strUsrS.trim());
parameters.put(Constant.TAG_PASS, strPassS.trim());
parameters.put(Constant.TAG_EMAIL, strEmailS.trim());
String pushId = mFirebaseInstance.getReference(Constant.FIREBASE_LOGIN).getRef().push().getKey();
parameters.put(Constant.TAG_KEY, pushId.trim());
mFirebaseInstance.getReference(Constant.FIREBASE_LOGIN).getRef().child(strUsrS.trim()).setValue(parameters);
Toast.makeText(Login_Reg_Activity.this, "Registered Successfully", Toast.LENGTH_SHORT).show();
finish();
Intent inMain = new Intent(Login_Reg_Activity.this, Login_Reg_Activity.class);
startActivity(inMain);
}else{
edtEmailS.setError("Enter a valid Email");
}
}else{
Toast.makeText(Login_Reg_Activity.this, "Fill all detail", Toast.LENGTH_SHORT).show();
}
After the successful registration, the data are stored in the users table in Firebase like this:
My doubt is that how to login using the credential username and mobile. I have tried by the reference link, but I couldn't succeeded. So, my kind request is to direct me to do this. Also, how to restrict the duplication on user registration?
Thanks in advance.
Step 1:
make sure you have enabled the password login in firebase console as shwon below in the picture
Use Below Code For Login with email and Pwd
FirebaseAuth mAuth = FirebaseAuth.getInstance(); // same auth as you used for regestration process
mAuth.signInWithEmailAndPassword("abc#abc.com","pwd")
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
}
}})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
when you get successfully login than auth change listner will be invoke
Auth Change Listner
private FirebaseAuth.AuthStateListener mAuthListener;
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user !=null){
}
}
};
mAuth.addAuthStateListener(mAuthListener);

Android-How to get User info from Firebase after logging in

With my current login activity, I can log in just fine, however I need to get Uid throughout my project.
This is my current login activity:
//authenticate user
firebaseAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// 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.
progressbar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
lPass.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(LoginActivity.this, MapsActivity.class);
startActivity(intent);
finish();
}
}
});
}
});
How do I get the user Uid from the login and have it be accessible to all my other activities?
Thanks
You can get user info from the FirebaseUser object. In order to achieve this, please use the following code:
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseAuth.AuthStateListener authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
String userId = firebaseUser.getUid();
String userEmail = firebaseUser.getEmail();
}
}
};
FirebaseAuth.getInstance().getCurrentUser().getUid();
This line will give you the user ID.
This is a way to get all details available for user logged in from firebase.
FirebaseAuth mFirebaseAuth = FirebaseAuth.getInstance();
FirebaseUser mFirebaseUser = mFirebaseAuth.getCurrentUser();
// User Name
mFirebaseUser.getDisplayName();
// User ID
mFirebaseUser.getUid();
// Email-ID
mFirebaseUser.getEmail();
// User-Profile (if available)
mFirebaseUser.getPhotoUrl();
Using FirebaseAuth you can get user uid,
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
Log.d(TAG," UserId : "+firebaseUser.getUid()+" , DisplayName"+firebaseUser.getDisplayName());

implementing Android login features for new Firebase

I'm trying to update my android code in the new Firebase after May 2016's update, but am running into issues. Previously my user create worked fine with
Firebase ref = new Firebase("https://project.firebaseio.com");
ref.createUser(email, password, new Firebase.ValueResultHandler<Map<String, Object>>() {
#Override
public void onSuccess(Map<String, Object> result) {
System.out.println("Successfully created user account with uid: " + result.get("uid"));
error.setText("Account successfully created.");
}
#Override
public void onError(FirebaseError firebaseError) {
error.setText("Error with account creation");
}
});
but with the new system where I'm told I need to implement the system here: https://firebase.google.com/docs/auth/android/password-auth, I'm getting error
Cannot resolve method AddOnCompleteListener
whenever I try to put the method inside of an Android clickListener (how I'm sending the login data)
My (relevant) code is
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseAuth.AuthStateListener mAuthListener;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_login);
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());
} else {
// User is signed out
// Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
mCreateNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.email);
String email = editText.getText().toString();
editText = (EditText) findViewById(R.id.password);
String password = editText.getText().toString();
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(logStr, "createUserWithEmail: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()) {
Toast.makeText(getApplicationContext(), "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.email);
String email = editText.getText().toString();
editText = (EditText) findViewById(R.id.password);
String password = editText.getText().toString();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(logStr, "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(logStr, "signInWithEmail", task.getException());
Toast.makeText(getApplicationContext(), "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
});
Reading through the new Firebase guide, it mentions that these new listeners wait for an update on the user's "sign in state" but doesn't really go into detail on that. How do I make it so that I can call the sign-in/create-new only when I click the buttons?
I know that taking the code outside of the clicklistener "solves" the problem, but then I don't know how to be able to control when the user sends login data.
I found a similar question that answers mine Firebase 9.0.0 mAuth.signInWithEmailAndPassword, how to pass it to a button
It seems that this issue is common enough that it necessitates more clarification on the Firebase site. Basically, .addOnCompleteListener() needs to be declared as it's own class within the login activity.
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {

Categories

Resources