Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add name, profile pic, address of a user to Firebase Database?

I m trying to make an Android app in which I want to save each user personal details like name, profile pic, and address to Firebase Database for future use.

Please suggest me how can I do that?

like image 513
anubhav singh Avatar asked Sep 26 '16 13:09

anubhav singh


3 Answers

You have not invested time in getting familiar with These Firebase Docs. This is the reason why there are so many down-votes to your question. Still I would like to give you a brief overview of what Firebase gives you:

//This is how you can get the user profile data of each logged in user

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    // Name, email address, and profile photo Url
    String name = user.getDisplayName();
    String email = user.getEmail();
    Uri photoUrl = user.getPhotoUrl();

    // The user's ID, unique to the Firebase project. Do NOT use this value to
    // authenticate with your backend server, if you have one. Use
    // FirebaseUser.getToken() instead.
    String uid = user.getUid();
}

//This is how you can update user profile data of each logged in user

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

If you you are using firebase without implementing any authentication and security rules then I would say you should change it asap. As without authentication and proper security rules any one can get access of your database and alter it in any manner he/she wants to.

For logged in users you need not do anything extra or special to save their profile details. If you use auth providers like Gmail, Facebook then basic profile info is automatically saved by firebase. If you are using some custom auth method then refer to update user profile code snippet provided by firebase. That's how you save basic user profile.

Do let me know if this helps you.

like image 132
Nishant Dubey Avatar answered Oct 24 '22 20:10

Nishant Dubey


Got help from Nishants answer and this is what worked for my current project using Kotlin.

fun registerUser(email: String, password: String, displayName: String) {
        auth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(requireActivity()) { task ->
                if (task.isSuccessful) {
                    // Sign in success, update UI with the signed-in user's information
                    Log.d(TAG, "createUserWithEmail:success")

                    val user = auth.currentUser

                    val profileUpdates =
                        UserProfileChangeRequest.Builder()
                            .setDisplayName(displayName)
                            .setPhotoUri(Uri.parse("https://firebasestorage.googleapis.com/v0/b/fakelogisticscompany.appspot.com/o/default.png?alt=media&token=60224ebe-9bcb-45fd-8679-64b1408ec760"))
                            .build()

                    user!!.updateProfile(profileUpdates)
                        .addOnCompleteListener { task ->
                            if (task.isSuccessful) {
                                Log.d(TAG, "User profile updated.")
                            }
                        }

                    showAlert("Created your account successfully!")

                    updateUI(user)
                } else {
                    // If sign in fails, display a message to the user.
                    Log.w(TAG, "createUserWithEmail:failure", task.exception)

                    showAlert("Authentication failed!")

//                    updateUI(null)
                }
            }
    }

I am creating the user and updating the details right after. showAlert and updateUI are my own functions to show the alertdialog and redirecting the user. Hope this will help someone else in the near future. Happy coding!

like image 37
thesamoanppprogrammer Avatar answered Oct 24 '22 21:10

thesamoanppprogrammer


I used this code in my project. It works for me. signUp.dart

 onPressed: () {
                  FirebaseAuth.instance.createUserWithEmailAndPassword(
               email: _email, password: _password).then((signedInUser) {
                   _uid= signedInUser.uid;
                    Map<String,String> userDetails = {'email':this._email,'displayName':this._displayname,'uid':this._uid,
                      'photoUrl':this._photo};
                    _userManagement.addData(userDetails,context).then((result){
                    }).catchError((e){
                      print(e);
                    });
                  }).catchError((e) {
                    print(e);
                  });

                },

userManagement.dart

 Future<void> addData(postData,context) async{
  Firestore.instance.collection('/users').add(postData).then((value){
    Navigator.of(context).pop();
    Navigator.of(context).pushReplacementNamed('/homepage');
  }).catchError((e){
    print(e);
  });
}
like image 20
Hasini Avatar answered Oct 24 '22 21:10

Hasini