Firebase setDisplayName of user while creating user Android - android

When creating a user, I want to be able to set his/her display name. How do I do this in Android? Here is an example of what I want to achieve:
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
FirebaseUser.getCurrentUser().setDisplayName(mName); //I want to do this
}
});
Assume all variables have been declared and/or initialized correctly.

You can set the user's Firebase display name by writing the following three lines of code:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(mName).build();
user.updateProfile(profileUpdates);
By doing so, your original code should look like this:
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
// Sign in is successful
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(mName).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.");
}
}
});
}
});
Official Firebase Documentation:
Firebase Update a User's Profile
What the above code does is that when the user's account is successfully created using Email and Password authentication, it will then sign-in the user.
Once the user is signed-in, you can access the user's Firebase User Object Properties and set the display name property to any string you want.
This is great for testing the user's profile name in Verification Emails.
Note: A Firebase User Object has a fixed set of basic properties—a unique ID, a primary email address, a name, and a photo URL. These basic properties are stored in the project's User Database.
Furthermore, these properties can be updated programmatically.
However, you cannot add other properties to the Firebase User Object directly; instead, you can store any additional properties (i.e. user information) in your Firebase Realtime Database, and reference them from there.
(Firebase User Object Properties Doc)

I found the answer in the Firebase docs. I will quote it here: "If sign-in succeeded, the AuthStateListener runs the onAuthStateChanged callback. In the callback, you can use the getCurrentUser method to get the user's account data." Here is the link: https://firebase.google.com/docs/auth/android/password-auth#sign_in_a_user_with_an_email_address_and_password
So that means, if you do the above code (minus the FirebaseUser line), and then declare and initialize a Firebase AuthStateListener like shown below, you can set the user's display name and then move on to any other activity you want:
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user!=null){
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(mName).build();
user.updateProfile(profileUpdates);
Intent intent = new Intent(currentActivity.this, nextActivity.class);
startActivity(intent);
}
}
};
And don't forget to add the AuthStateListener in onResume() like so:
#Override
public void onResume(){
super.onResume();
mAuth.addAuthStateListener(mAuthListener);
}
Likewise, don't forget to remove it in the onStop method like so:
#Override
public void onStop(){
super.onStop();
if(mAuthListener != null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
And done! You set the user's display name so you can use it in other activities. This would be useful if you want to greet the user or access any other user data tied to the display name.

Related

Signing out from Firebase recall signinwithemailandpassword

The situation is the following:
The activity started on app's launch (let's call it splash activity, because used for some checkings and for read/write some settings) is made by frameworks and the last one of them has firebase signInWithEmailAndPassword whose addOnCompleteListener contains the code for starting a new activity (let's say the main activity).
one of the options of the (so called) main activity's menu is firebase signOut, when i tap it the current user signs out but the signInWithEmailAndPassword (coded into the last fragment of previous activity) is called again!
is it because i splitted sign-in and sign-out in two different activities?
can anybody kindly help me with that, thanks in advance.
here is code schema:
FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password)
.addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// read some data from realtime database
database
.getReference(path)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
get snapshot data ...
// Store them into shared preferences
mSettings
.edit()
.putStringSet("STRING_SET_KEY", dataSet)
.apply();
// Update some Realtime database data
database
.getReference(path)
.updateChildren(newData)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
// Start new activity
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
});
});
});
});
}
});
});
p.s. - i noticed because the signOut() kicks out the firebase user and when the signInWithEmailAndPassword is called again i got an error because it's not possible to read realtime database
You may check whether the user is still sign in or not.
According to this link: https://firebase.google.com/docs/auth/android/manage-users
This code put at the onCreateView...
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// User is signed in
// Start new activity
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
} else {
// No user is signed in
}

Firebase Authentication (email and password) How to check if user still exists?

I'm using Firebase Authentication in my app (email and password auth).
In the onStart() method of my Login activity I retrieve the current user using:
FirebaseUser currentUser = mAuth.getCurrentUser();
The problem comes when the user is deleted from the database, the mAuth.getCurrentUser() method still retrieves the user and allows authentication.
How can I check if the user still exists?
Thx!
Try using something like this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("users").child("email").addListenerForSingleValueEvent(new
ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
// used "email" already exists and is not deleted
} else {
// User does not exist. Add here your logic if the user doesn't exist
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Or check some of the following SO questions and answers:
Firebase authentication for checking if the user exists in the database or not
Firebase Auth - with Email and Password - Check user already registered
You can use getInstance. This worked for me fine. You don't get an instance with it.
private boolean isSignedIn() {
return FirebaseAuth.getInstance().getCurrentUser() != null;
}
Delete the userdata and make the currentuser null:
Follow the below code.
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.delete()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User account deleted.");
//Remove the information f the user from database.
}
}
});
The code below works great on android to confirm if the Firebase Auth user still exists (has not been deleted or disabled) and has valid credentials.
Deleting the Auth user from the firebase console does not revoke auth tokens on devices the user is currently logged in as the token is cached locally. Using reload() forces a check with the firebase auth server.
currentUser.reload().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
//User still exists and credentials are valid
}else {
//User has been disabled, deleted or login credentials are no longer valid,
//so send them to Login screen
}
}
});

Firebase Authentication: Setting User properties like name, phone, etc

How can store additional user properties in firebase like user's name, phone number programatically? Do I need to create additional document for every user to store their properties?
I'm creating user using like
userAuth.createUserWithEmailAndPassword(userBO.getUserPhoneNumber(),userBO.getUserPassword()).addOnCompleteListener(
getActivity(), new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//TODO: set user properties here
}
else{
}
}
}
);
You should not use User Properties for saving static data like name, Phone number etc. As this data is specifically used for analytics purpose. Instead I would suggest you to create another document in firebase for storing user specific details.
You can set userName and photo as:-
UserProfileChangeRequest userProfileChangeRequest = new UserProfileChangeRequest.Builder().setPhotoUri(uri).setDisplayName(name).build();
userAuth.getCurrentUser().updateProfile(userProfileChangeRequest).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
});

How to check whether a user is authenticated or not in Firebase?

I have a few sign-up methods in my app as shown below:
Let's revolve the problem around Google sign-in method:
What I am doing is that when a user signs in enteringDataIntoUserNode() method is called inside signInWithCredential() method like:
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
AuthCredential credential =
GoogleAuthProvider.getCredential(acct.getIdToken(), null);
// signing in
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// entering default values in the database
enteringDataIntoUserNode();
Intent intent = new Intent(LoginAndSignupActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else {
Log.w(TAG, "signInWithCredential:failure", task.getException());
}
}
});
}
enteringDataIntoUserNode()
private void enteringDataIntoUserNode() {
final String currentUid = mAuth.getCurrentUser().getUid();
//
String deviceToken = FirebaseInstanceId.getInstance().getToken();
final String userName = mAuth.getCurrentUser().getDisplayName();
String imageUrl = mAuth.getCurrentUser().getPhotoUrl().toString();
String userStatus = "Hi there! How is it going?";
// inserting data in key-value pair
usersReference.child(currentUid).child("user_name").setValue(userName);
usersReference.child(currentUid).child("user_status").setValue(userStatus);
usersReference.child(currentUid).child("user_image").setValue(imageUrl);
usersReference.child(currentUid).child("device_token").setValue(deviceToken);
// when this last value will be inserted then, making an intent to MainActivity
usersReference.child(currentUid).child("user_thumb_image").setValue(imageUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Log.d(TAG, "onComplete: Data insertion for the new user is successful ");
}
}
});
}
enteringDataIntoUserNode() method is simply passing some default data to the database every time a user signs in. But if a user change its details like image or username etc. and sign out and again sign in through Google sign in method then again enteringDataIntoUserNode() method will be called and user details would be overwritten with the default ones.
My question is that is there any way to check whether a user is signing in for the first time or not during the Google sign in so that in the latter case I can skip calling enteringDataIntoUserNode() method and prevent overwriting of data.
Same thing I want to acheive during Facebook and Phone Number sign in.
If you check if the user logs in for the first time, it's the same thing if you want to check if a user is new. So to solve this, we can simply call the isNewUser() method in the OnCompleteListener.onComplete callback like this:
OnCompleteListener<AuthResult> completeListener = new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
boolean isNewUser = task.getResult().getAdditionalUserInfo().isNewUser();
if (isNewUser) {
Log.d("TAG", "The user is new!");
} else {
Log.d("TAG", "The user is not new!");
}
}
}
};
For more informations, please see the official documentation.
You could check when the account was created with:
task.getResult().getUser().getMetadata().getCreationTimestamp()
See the reference docs.
But a common approach is also to check if the user already exists in the database using a transaction.

New to firebase auth and android development

I am pretty new to android development and Firebase(the new google one). I want to use the email and password feature, but sign specific users in(the ones in my firebase console). I know this is a pretty broad question, but any help would be much appreciated.
First of all, you should check a documentation for Firebase. You can find on official Firebase website:
1. https://firebase.google.com/docs/auth/android/manage-users
2. https://firebase.google.com/docs/auth/android/password-auth
Then you should check Firebase Authentication samples and look for Email/Password Setup.
After you have created your project and added your app to it, you have to go to the console/auth/sign_in method and enable the email and password authentication. Then you have to create a activity/fragment to represent the login, sign up etc.
On the launcher activity you should have this method to check the state of current user and do the necessary action of user != null or if user == null based on your preferences.
FirebaseAuth.AuthStateListener authStateListener;
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null){
startActivity(new Intent(LoginPage.this,MainActivity.class));
}
}
};
auth.addAuthStateListener(authStateListener);//this one in onStart
then you can use these 2 methods for signin and create new user respectively
FirebaseAuth auth;
auth = FirebaseAuth.getInstance();
auth.signInWithEmailAndPassword(email , password)
.addOnCompleteListener(LoginPage.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
}else {
}
}
});
auth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(SignUpPage.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
}else {
}
}
});
go to all the links provided by mmBs and also see this link for a simple and working example

Categories

Resources