how to change firebase user in andorid [duplicate] - android

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.

Related

Firebase Realtime Database, setValue() does nothing

Edit: problem solved by moving setValue(newProfile) below createUserWithEmailAndPassword method.
I am trying to register people and put their information to database using Firebase in the same activity. There is no problem registering them. But even though user is registered, MainActivity starts and then toast message shows up; setValue() under the same method with these commands doesn't write informations to database. Here is writing to database part (setValue() parameter newProfile is declared as HashMap<>()):
mAuth = FirebaseAuth.getInstance();
firebaseAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null){
databaseReference = FirebaseDatabase.getInstance().getReference().
child(selected_server).child(user_role).child(user.getUid());
databaseReference.setValue(newProfile);
Toast.makeText(Registration.this,"Registration completed!",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Registration.this,MainActivity.class);
startActivity(intent);
finish();
}
}
};
and here is the registration part:
btn_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = et_email.getText().toString();
final String password = et_password.getText().toString();
if(needed_role.equals("") || user_role.equals("") || selected_server.equals("") ) {
Toast.makeText(Registration.this,"Please complete all informations" , Toast.LENGTH_SHORT).show();
}
else{
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(Registration.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
newProfile.put("E-mail" , et_email.getText().toString());
newProfile.put("Password" , et_password.getText().toString());
newProfile.put("Server" , selected_server);
newProfile.put("Summoner Name",et_summoner_name.getText().toString());
newProfile.put("Role", user_role);
newProfile.put("Needed" , needed_role);
if(!task.isSuccessful()){
Toast.makeText(Registration.this,"Sign up error" + task.getException(),Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
Use updateChildren
Make sure you are not using the hashmap before putting value into it
final DatabaseReference databaseRef =FirebaseDatabase.getInstance().getReference().
child(selected_server).child(user_role).child(user.getUid();
databaseRef.updateChildren(newProfile)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
});

No linked databased of the user is being created during registration - Firebase

I'm trying to make a user authentication with Firebase and at the same time store the user Full name and email address in the database linked with the User UID that is created during authentication. Here, my database table name is Users and I have been trying the following code to link my user information with its UID.
With the following code, the user gets registered but no associated database is being formed. What am I doing wrong here? Thanks in advance for the suggestion.
public class SignUpActivity extends AppCompatActivity implements View.OnClickListener {
EditText editTextFullName, editTextEmail, editTextPassword;
private FirebaseAuth mAuth;
FirebaseDatabase database;
DatabaseReference ref;
Users users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
editTextFullName = (EditText) findViewById(R.id.editTextFullName);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
database = FirebaseDatabase.getInstance();
ref = database.getReference("Users");
users = new Users();
mAuth = FirebaseAuth.getInstance();
findViewById(R.id.buttonSignUp).setOnClickListener(this);
}
private void getValues() {
users.setFullName(editTextFullName.getText().toString());
users.setEmail(editTextEmail.getText().toString());
}
private void registerUser() {
final String fullname = editTextFullName.getText().toString().trim();
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
finish();
startActivity(new Intent(SignUpActivity.this, ProfileActivity.class));
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
getValues();
ref.child(""+ user +"").setValue(users);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
if (task.getException() instanceof FirebaseAuthUserCollisionException) {
Toast.makeText(getApplicationContext(), "You are already registered", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonSignUp:
registerUser();
break;
}
}
}
Something like this:
Do not forget the executor class,this is a proper example:
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignupActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(SignupActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
// 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(SignupActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(SignupActivity.this, MainActivity.class));
finish();
}
}
});
}
});
}
you are finishing the activity before it can write to database when you call
finish();
method
fire the intent once the data has been written to database i.e after
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
getValues();
ref.child(""+ user +"").setValue(users);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
startActivity(new Intent(SignUpActivity.this, ProfileActivity.class));
finish();
like this
You don't need value event listener for that you can directly add to database like this :
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("users");
databaseReference.push().setValue(users);
and you have to call finish(); after the database call
Start Activity and call finish() after setting the value to Database as #Rohit has suggested.
One more suggestion is; if you want to save data using UID, you will have to set it in the reference path like below:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users");
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
String UID = user.getUid(); //get UID of currently logged in user(new user in your case)
ref.child(UID).setValue(users); //this will give you expected structure
startActivity(new Intent(SignUpActivity.this, ProfileActivity.class));
finish();
}

Firebase Realtime Database & Auth

I have recently adopted Firebase for my Backend work. Using Firebase I want to store all the user data like username, phone number, etc to Firebase in the same RegisterActivity and not just Email & Password. How can I achieve this ?
My RegisterActivity will only appear at the time of installation. When user have register to my app, I am destroying the activity. So, there is no instance of RegisterActivity further.
RegisterActivity - onCreate():
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
setContentView(R.layout.activity_register);
initialization();
underlineText(); //Underlining Text in App
userObj = new User();
userObj.setName(NAME);
userObj.setEMAIL(EMAIL);
userObj.setPHONE(PHN);
animShake = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.shake); //Animation
vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); //Vibration
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitForm(); //Registration Click Listener
}
});
skip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
skipRegistrationSection(); //Skip Click Listener
}
});
runAtInstallation();
}
submitform():
private void submitForm() {
if (!checkName()) {
name.setAnimation(animShake);
name.startAnimation(animShake);
vib.vibrate(60);
return;
}
if (!checkEmail()) {
email.setAnimation(animShake);
email.startAnimation(animShake);
vib.vibrate(60);
return;
}
if (!checkPhone()) {
phone.setAnimation(animShake);
phone.startAnimation(animShake);
vib.vibrate(60);
return;
}
if (!checkPassword()) {
password.setAnimation(animShake);
password.startAnimation(animShake);
vib.vibrate(60);
return;
}
if (!checkConfirmPassword()) {
confirmPassword.setAnimation(animShake);
confirmPassword.startAnimation(animShake);
vib.vibrate(60);
return;
}
nameLayout.setErrorEnabled(false);
emailLayout.setErrorEnabled(false);
phoneLayout.setErrorEnabled(false);
passwordLayout.setErrorEnabled(false);
confirmPasswordLayout.setErrorEnabled(false);
NAME = name.getText().toString().trim();
EMAIL = email.getText().toString().trim();
PHN = phone.getText().toString().trim();
PASSWORD = password.getText().toString();
progressBar.setVisibility(View.VISIBLE);
authUser(); //authenticating User via Email & Password
}
authUser():
private void authUser() {
mFirebaseAuth.createUserWithEmailAndPassword(EMAIL, PASSWORD).addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage(task.getException().getMessage())
.setTitle("Error")
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
progressBar.setVisibility(View.GONE);
} else {
progressBar.setVisibility(View.GONE);
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
});
}
runAtInstallation:
private void runAtInstallation() {
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if (pref.getBoolean("activity_executed", false)) {
Intent act = new Intent(getApplicationContext(), MainActivity.class);
act.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
act.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(act);
finish();
} else {
SharedPreferences.Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
}
}
I want to save name,email,& phone in the firebase database during registration and to destroy the activity after that.
I'm working on the same problem right now. The thing is, sign-IN (authentication) and sign-UP (registration) are two different things.
What I have done is have two separate activities, signIN... and signUP (register).
Once the user is signed up (email and password), they will have a unique userID known to Firebase.
Next, they go to the registration activity, so when you "upload" all the data from the editTexts in this activity, you can upload them to a node (key... index) in your database that matches the userID... so your data in your database looks like:
\ mydatabase \ users \ [uniqueID] \
If you combine both activies (authentication and registration) into one... with many fields, "email, password, name, phonenumber, etc." all in one activity, then you're going to still need to make a separate signIN only activity for the next time they run the app with an expired session. I think it's much simpler to do two separate activites.
I have one activity and I simply try to register right away regardless if the user exists or not and then if the error is due to the email existing already I sign the user in instead of registering them.
mAuth = FirebaseAuth.getInstance();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
if(task.getException() instanceof FirebaseAuthUserCollisionException) {
// login user
}
else {
// handle error
}
}
else {
// register user
}
}
You can add user profile information and other details like
For update profile
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName("Jane Q. User")
.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.");
}
}
});
For more details to manage user details please refer this link Firebase manage user

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

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

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