I registered a user by using createUserWithEmailAndPassword() and login using signInWithEmailAndPassword() methods. Now when I login a user I need to get the username, mobile, that are stored in the user node. I could get the UId for each user, by using this how it possible to get the mentioned information in android?
all you have to do is use UserProfileChangeRequest
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
// Sign in success
FirebaseUser user = mAuth.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.");
}
}
});
}
});
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();
}
or you can create your own custom node.!
String currentuser = FirebaseAuth.getInstance().getUid();
//save user node after successful signup.
mFirebaseInstance.getReference("user").child(scurrentuser ).setValue(parameters);
databaseReference = FirebaseDatabase.getInstance().getReference().child("user").child(currentuser );
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot userSnapShot: dataSnapshot.getChildren()){
User user = userSnapShot.getValue(User.class);
}
}
Related
I've registered an account in my Android application using Firebase and there are multiple textfields.
How can I assign particular textfield as displayName of user so that I can later access it using getDisplayName()?
To change a user's display name, you need to update the user 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.");
}
}
});
Everything worked but not showing name only.
My code is:
user = profAuth.getCurrentUser();
if (user != null) {
// Name, email address
String uid = user.getUid();
String name = user.getDisplayName();
String email = user.getEmail();
txtName.setText(name);
txtEmail.setText(email);
txtUserid.setText(uid);
}
That's because Firebase Auth doesn't prompt the user to provide a Display name when signing up with Email/Password. But you can do that manually. Prompt the user to type the display name he desires, and pass it to the setDisplayName() method bellow:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(desiredName)
.build();
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User display name updated.");
}
}
});
I am using Firebase user sign up method with email and password. While creating a new user I also store information such username that later on needs to be displayed in app profile page.
How could I retrieve the username of currently logged in person ?
Thank you in advance
private void registration(){
final String email = Email.getText().toString().toString().trim();
final String password = Password.getText().toString().trim();
final String username = Username.getText().toString().trim();
final String age = Age.getText().toString().trim();
final String userID = userAuth.getCurrentUser().getUid();
if (!TextUtils.isEmpty(email)&& !TextUtils.isEmpty(password)&& !TextUtils.isEmpty(username)&& !TextUtils.isEmpty(age)){
showProgress.setMessage("Registration in progress...");
showProgress.show();
userAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
String user_id = userAuth.getCurrentUser().getUid();
DatabaseReference current_user_db = DatbaseOfUsers.child(user_id);
current_user_db.child("email").setValue(email);
current_user_db.child("username").setValue(username);
current_user_db.child("Age").setValue(age);
current_user_db.child("uID").setValue(userID);
showProgress.dismiss();
//After user is created main screen intent is called
Intent mainpage = new Intent(RegisterActivity.this, MainPageActivity.class);
mainpage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainpage);
}
else if(!task.isSuccessful()){
showProgress.dismiss();
Toast.makeText(RegisterActivity.this,"Error While Register",Toast.LENGTH_LONG).show();
}
}
});
}
else{
showProgress.dismiss();
Toast.makeText(RegisterActivity.this,"Please Enter All Required Fields",Toast.LENGTH_LONG).show();
}
private FirebaseAuth mAuth;
mAuth = FirebaseAuth.getInstance();
final FirebaseUser Theuser = mAuth.getCurrentUser();
if (Theuser !=null)
_UID = Theuser.getUid();
You can send request to Users with current user's uid.
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("Users").orderByChild(currentUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
In onDataChange returns value you are looking as dataSnapshot. Then cast it to your model, get the want ever you want.
I used this code sinppet to update the current Firebase user which have signed up using createUserWithEmailAndPassword() method:
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.");
}
}
});
But when I try retrieve the diplayName or photoUri, they return null as if they've never been set in the first place.
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();
}