3
votes

In one activity, I am signing in the user, and it moves on to another activity where the user is greeted. I am using the built-in Firebase methods for signing in a user using email/password. I have the UID in Firebase Database and this is linked with a name. I am just manually inputting users in Firebase and will implement a sign up activity later. How do I access the UID of the user in the second activity?

3

3 Answers

5
votes

Alternatively to passing the uid around, you can use an auth state listener to detect the user in each activity. From that documentation page:

mAuthListener = new FirebaseAuth.AuthStateListener() {
    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        FirebaseUser user = firebaseAuth.getCurrentUser();
        if (user != null) {
            // User is signed in
            Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
        } else {
            // User is signed out
            Log.d(TAG, "onAuthStateChanged:signed_out");
        }
        // ...
    }
};

This code would typically go into a base-class that you derive your activities from.

2
votes

just use

FirebaseAuth mAuth;

mAuth = FirebaseAuth.getInstance();

FirebaseUser user = mAuth.getCurrentUser();

String UID = user.getUid();

It will automatically get user from previous acivity.

0
votes

You should either save it in SharedPreferences and retrieve it in the second activity or pass it into the second Activity via the Intent object.

SharedPreferences is one of the simpler ways to store data persistently in the app. Data stored in SharedPreferences can be retrieved and modified from almost anywhere in the app. Data will survive phone restarts, and even an app uninstall, because it can be backed up by the system. Here is the official explanation. And here is a good tutorial.