I'm trying to create an profile activity, where users can change those Profile picture and Display name, I'm trying to update user photo or user name, CompleteListener called, task.isSuccessful = true but nathing done, why?
Function to update name:
FirebaseUser mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final String newName;
newName = input.getText().toString();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(newName)
.build();
mFirebaseUser.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
DatabaseReference mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference().child("users");
mFirebaseDatabaseReference.child(mFirebaseUser.getUid()).child("DisplayName").setValue(newName);
updateUI();
Toast.makeText(ProfileActivity.this, "User display name updated.", Toast.LENGTH_SHORT).show();
} else
Toast.makeText(ProfileActivity.this, "Error while updating display name.", Toast.LENGTH_SHORT).show();
}
});
Same when i'm trying to update Profile picture that I just uploaded to Firebase Storage...
And idea?
EDIT:
Sometimes the username really get updated, I think it's take like more then 10 minutes to update, why?
I have had a similar problem where the User information was not updating until the User re-authenticated. I resolved it by also saving this information in my firebase database. For me this made sense, as I wanted Users to be able to get basic information about other Users anyway.
My code ended up looking something like this. When the account is created, or modified, I made a call to the "users/{uid}" endpoint and updated the object there. From here I used the GreenRobot EventBus to send my new User object to whoever was subscribed so that it would be updated on the screen.
private FirebaseUser firebaseUser;
public void createUser(String email, String password, final User user, Activity activity, final View view) {
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(activity, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());
// If sign in fails, display a messsage to the user. If sign in successful
// the auth state listener will be notified and logic to handle
// signed in user can be handled in the listener
if (!task.isSuccessful()) {
Snackbar.make(view, task.getException().getLocalizedMessage(), Snackbar.LENGTH_SHORT).show();
} else {
firebaseUser = task.getResult().getUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(user.displayName)
.build();
firebaseUser.updateProfile(profileUpdates);
updateDatabase(user);
EventBus.getDefault().post(new LoginEvent());
}
}
});
}
public boolean updateDatabase(User user) {
if (firebaseUser == null) {
Log.e(TAG, "updateDatabase:no currentUser");
return false;
}
return userReference.setValue(user).isSuccessful();
}
The setup of the database watcher was done something like this. Note that you need to make sure that you remove the listener when the User logs out and add a new one when the User logs in.
protected void setupDatabaseWatcher() {
String uid = firebaseUser.getUid();
userReference = FirebaseDatabase.getInstance().getReference("users/" + uid);
userReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
User user = dataSnapshot.getValue(User.class);
Log.d(TAG, "Value is: " + user);
EventBus.getDefault().post(new UserUpdateEvent(user));
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
Use this simple code:
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(newName)
.build();
Related
Want to update profile, started with email to get the hang off. Whenever I click on it to update the email, it adds a new UID for that email alone instead of adding it to the user profile with that UID. Really stuck now. I did have it working but cant seem to get back to it so must be an error here somewhere, thanks,
updateProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String updateEmail = emailTextView.getText().toString();
user.updateEmail(updateEmail).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
firebaseDatabase.getReference("Users").child(user.getUid()).child("email").setValue(updateEmail);
Toast.makeText(getApplicationContext(), "Email update", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
}
UPDATE
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
final String uid = firebaseUser.getUid();
Log.d(TAG, "USERID="+uid);
Doin this got me a UID from a completely different user! It did let me change the email for them when I did this but thats no use. Having similar issues deleting users. Is it an issue with a UID does it create a new one everytime they log in?
I want to give the user in my app the possibility to delete his account so when he clicks on the delete button a document gets deleted which contains all his informations. The name of the document is his displayName so I get this as a string but when I run the code you are seeing below I get a NullpointerException in this line:
String currentUsername = user.getDisplayName();
even though the displayName is not null.
Edit:
I found the solution on my own, see the answer below.
Here is my method:
btn_delete_account.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.delete()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
deleteDocument();
}
}
});
}
});
...
public void deleteDocument (){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String currentUsername = user.getDisplayName();
db.collection("User").document(currentUsername)
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully deleted!");
Toast.makeText(PersonalSettings.this, "Your account was successfully deleted.", Toast.LENGTH_SHORT).show();
Intent i = new Intent(PersonalSettings.this, SignInActivity.class);
startActivity(i);
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error deleting document", e);
}
});
}
First thing you have to check that current user is not null
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user==null)
{
return;
}
if current user is not null then get its name and further check that it's name is not null.
String currentUsername = user.getDisplayName();
if(TextUtils.isEmpty(currentUsername))
{
return;
}
if name is not null then go for delete document as follows :
public void deleteDocument (){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user==null)
{
return;
}
String currentUsername = user.getDisplayName();
if(TextUtils.isEmpty(currentUsername))
{
return;
}
db.collection("User").document(currentUsername)
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully deleted!");
Toast.makeText(PersonalSettings.this, "Dein Account wurde erfolgreich gelöscht.", Toast.LENGTH_SHORT).show();
Intent i = new Intent(PersonalSettings.this, SignInActivity.class);
startActivity(i);
finish();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error deleting document", e);
}
});
}
I think you're misunderstanding the error. It's saying that user is null, not the display name. This means there is currently no user signed into the app. You will have to write some code to check for this case.
I also strongly suggest not using a display name as the ID for a document in Cloud Firestore. Since you're using Firebase Authentication, the user already has a unique ID assigned to their account. This is the preferred way to store per-user data.
I found the error:
I called my delete method after I used the user.delete() method which deletes the signed in user, so logically the displayName was also deleted.
I am making an android application using Firebase database and I want to check that the user is not in registered as an "Association" so I am checking if he belongs to the child "Association".
The method userLogin is supposed to not log in the user if he is under the child "Associations" and log in him otherwise.
However, it is not working and the user is logged in even if he is under "Associations"
private void userLogin() {
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
String RegisteredUserID = currentUser.getUid();
DatabaseReference jLoginDatabase = FirebaseDatabase.getInstance().getReference().child("Associations").child(RegisteredUserID);
jLoginDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Toast.makeText(getApplicationContext(), "You are not registered", Toast.LENGTH_SHORT).show();
}
else
{
finish();
Intent intent = new Intent(SignInDonor.this, homedonor.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}});}
else {
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
I did not tried this, but it should work, first, after you log in with a user and enters inside task.isSuccessful , you can retrieve the current logged in user with task.getResult().getUser().getUid(). Then just loop inside Associations and get each user key (I assume that Associations has userIDs inside as nodes with a certain value), then compare if the current logged in user is equal to one inside that node, if matchs it will pop up your Toast, if not you will be redirected.
Try this
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
DatabaseReference jLoginDatabase = FirebaseDatabase.getInstance().getReference().child("Associations");
jLoginDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
if(snapshot.getKey().equals(task.getResult().getUser().getUid()) {
Toast.makeText(getApplicationContext(), "You are not registered", Toast.LENGTH_SHORT).show();
}
else
{
finish();
Intent intent = new Intent(SignInDonor.this, homedonor.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
I used addListenerForSingleValueEvent because we only need to loop once at the reference and not keep listening for data
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);
I'm new android learner so its is difficult for me to do stuffs which I cannot find in the documentation. Here is my code for creating users
mAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//Successfully Registered
Toast.makeText(RegisterActivity.this, "Registration Successful", Toast.LENGTH_SHORT).show();
}else {
//Error occurred during registration
Toast.makeText(RegisterActivity.this, "Registration Unsuccessful", Toast.LENGTH_SHORT).show();
try {
throw task.getException();
} catch(FirebaseAuthWeakPasswordException e) {
editTextPassword.setError(e.getMessage());
editTextPassword.requestFocus();
}catch(FirebaseAuthUserCollisionException | FirebaseAuthInvalidCredentialsException e) {
editTextEmail.setError(e.getMessage());
editTextEmail.requestFocus();
} catch(Exception e) {
Log.e(RegisterActivity.class.getName(), e.getMessage());
}
}
progressDialog.dismiss();
}
});
This only takes two parameters(email and password) to create an user. To create user with more fields what approach should I take.
I have also added a FirebaseAuth.AuthStateListener() to check user login status. But when I'm calling firebaseAuth.getCurrentUser().getDisplayName() after successfully user login it returns null as usual.So how can I create user with Names so I can retrieve it with firebaseAuth.getCurrentUser().getDisplayName().
After the registration is successful,
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName("Jane Q. User")
.build();
EDIT: This code is a bit incomplete as profileUpdates is never accessed.
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User profile updated.");
}
}
});
Then, to retrieve it, use this wherever required,
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// Name, email address etc
String name = user.getDisplayName();
String email = user.getEmail();
}
To add a user with extra information such as User's name or other required information you should store these data using the Firebase real-time database under the unique user_id generated upon successful completion of email and password registration.
Get user input for name in registration form,
String name = mNameField.getText().toString().trim();
Add user's name in onComplete method :
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
String user_id = mAuth.getCurrentUser().getUid;
DatabaseReference current_user = mDatabase.child(user_id);
current_user.child("name").setValue(name);
progressDialog.dismiss();
}