How to store user data using Firebase in Android?

2020-07-31 11:42发布

问题:

I need to create and use a database entry with all details (uid, name etc) for each user that logs in to the application

I am having trouble storing user data in order to use and retrieve user profile info using Firebase in Android. I found this documentation on the old version of Firebase but this does not seem to work any longer.

Does anyone know how to reproduce the above code so it works with the new version of Firebase? Many thanks in advance.

Edit - code below:

final Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.authWithPassword("jenny@example.com", "correcthorsebatterystaple",
new Firebase.AuthResultHandler() {
@Override
public void onAuthenticated(AuthData authData) {
    // Authentication just completed successfully :)
    Map<String, String> map = new HashMap<String, String>();
    map.put("provider", authData.getProvider());
    if(authData.getProviderData().containsKey("displayName")) {
        map.put("displayName", authData.getProviderData().get("displayName").toString());
    }
    ref.child("users").child(authData.getUid()).setValue(map);
}
@Override
public void onAuthenticationError(FirebaseError error) {
    // Something went wrong :(
}
});

回答1:

For creating user in firebase database (new Version) ,you need to do changes as followning..

      private FirebaseAuth mAuth;
        String mUserEmail = "jenny@example.com";
        String mPassword = "correcthorsebatterystaple"

      mAuth.createUserWithEmailAndPassword(mUserEmail, mPassword)
     .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                    Log.d(LOG_TAG, getString(R.string.log_message_auth_successful) + " createUserWithEmail:onComplete:" + task.isSuccessful());

                    // if task is not successful show error
                    if (!task.isSuccessful()) {

                        try {
                            throw task.getException();
                        } catch (FirebaseAuthUserCollisionException e) {
                            // log error here                            

                      } catch (FirebaseNetworkException e) {
                            // log error here  
                        } catch (Exception e) {
                         // log error here        
                         }

                        } else {

                  // successfully user account created
                 // now the AuthStateListener runs the onAuthStateChanged callback

                    }
                }

            });
         }

now Add following method in onCreate() .

   final DatabaseReference ref = FirebaseDatabase.getInstance().
     getReferenceFromUrl(https://<YOUR-FIREBASE-APP>.firebaseio.com");
     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
             Map<String, String> map = new HashMap<String, String>();
             map.put("provider", user.getProvider());
             if(user.getProviderData().containsKey("displayName")) {
             map.put("displayName",  
             user.getProviderData().get("displayName").toString());
            } 
            ref.child("users").child(user.getUid()).setValue(map);
            } else {
                // User is signed out
                Log.d(LOG_TAG, "onAuthStateChanged:signed_out");
            }
        }
    };

   @Override
public void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);
}

@Override
public void onStop() {
    super.onStop();
    if (mAuthListener != null) {
        mAuth.removeAuthStateListener(mAuthListener);
    }

}


回答2:

  • To authenticate users with email and password (Google, Facebook) use Firebase Auth
  • To use Firebase database to store different data than use Firebase Realtime Database
  • If you want to Manage Auth users from your backend

User Management - Retrive user's full data and change a user's password or email address Custom Authentication - You can integrate an external user system with Firebase. Identity Verification - Use the service to identify these users on your own server.

Firebase Auth has a NODE JS sdk which you can use. If you want to access this features from Android, than you have to create a web service (eg.Restful API) and communicate with it through network.

  • If you want to access registered Auth users in Realtime Database i dont think you can because they are separated from each other. You can register users in Realtime Database but i dont understund why you want to do that since Auth provides you this feature in an easier way.

  • Firebase Realtime Database also has an Admin SDK (Java and Node JS)

    Please check documentation before asksing.



回答3:

Please use the latest Firebase SDK, found here: firebase.google.com/docs. Using the legacy SDK (as you are doing now) is just going to lead to a harder time than needed.

you can get user information as follows:

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    for (UserInfo profile : user.getProviderData()) {
        // Id of the provider (ex: google.com)
        String providerId = profile.getProviderId();

        // UID specific to the provider
        String uid = profile.getUid();

        // Name, email address, and profile photo Url
        String name = profile.getDisplayName();
        String email = profile.getEmail();
        Uri photoUrl = profile.getPhotoUrl();
    };
}