Skip to content
Advertisement

Why do we have to call getCurrentUser() several times Firebase?

I am creating a Journal app.

I am currently working on the functionality for if the user is already logged in—bypass the “get started/log in activities”

In the video I am watching to create a journal app, the instructor calls mUser = firebaseAuth.getCurrentUser(); several times.

He calls it in onStart(), in onCreate() and in onAuthStateChanged(). I can understand why we might need to call it again in onAuthStateChanged(), but in this case, I’m just checking if the user is already logged in, so it shouldn’t change from the user received in onCreate()

I removed it from onAuthStateChanged() and onStart() and everything is still working fine. However, I’m unsure if it will lead me to errors in the future. If anyone can confirm this, I would appreciate it. Is there a reason why we need to call getCurrentUser() several times? Thanks.

This is my full code for reference:

public class MainActivity extends AppCompatActivity {
    Button getStarted;

    private FirebaseUser mUser;
    private FirebaseAuth firebaseAuth;
    private FirebaseAuth.AuthStateListener myListener;
    private FirebaseFirestore db = FirebaseFirestore.getInstance();
    private CollectionReference myCollectionRef = db.collection("Users");


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        firebaseAuth = FirebaseAuth.getInstance();
        mUser = firebaseAuth.getCurrentUser();




        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getStarted = findViewById(R.id.btnGetStarted);

        getStarted.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
                finish();
            }
        });

        myListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull @NotNull FirebaseAuth firebaseAuth) {
                if(mUser != null){
                    //logged in
                    
                    //I commented this out and everything is still working fine
                    //mUser = firebaseAuth.getCurrentUser();
                    String currentUserId = mUser.getUid();

                    myCollectionRef.whereEqualTo("userId", currentUserId).addSnapshotListener(new EventListener<QuerySnapshot>() {
                        @Override
                        public void onEvent(@Nullable @org.jetbrains.annotations.Nullable QuerySnapshot value, @Nullable @org.jetbrains.annotations.Nullable FirebaseFirestoreException error) {
                            if(error != null){
                                Log.d("my_error", error.toString());

                            }

                            if(!value.isEmpty()){
                                for(QueryDocumentSnapshot snapshot : value){
                                    JournalApi myJournalApi = new JournalApi();
                                    myJournalApi.setUsername(snapshot.getString("username"));
                                    myJournalApi.setId(snapshot.getString("userId"));

                                    startActivity(new Intent(MainActivity.this, JournalList.class));

                                    finish();
                                }
                            }
                        }
                    });
                }else{
                    //not logged in
                }
            }
        };


    }

    @Override
    protected void onStart() {
        super.onStart();

        //I commented this out and everything is still working fine
        //mUser = firebaseAuth.getCurrentUser();
        firebaseAuth.addAuthStateListener(myListener);
    }

    @Override
    protected void onPause() {
        super.onPause();

        if(firebaseAuth != null){
            firebaseAuth.removeAuthStateListener(myListener);
        }
    }
}

Advertisement

Answer

While signing in is an active process, that your code triggers by calling one of the signInWith methods, maintaining the authentication state and restoring it on application restart are background processes that happen automatically when you use the Firebase SDK. This is great, because it means you don’t have to write code to keep tokens valid, or to check if the user profile has changed or their account has been disabled.

It does mean however that you can’t reliably cache the value of firebaseAuth.getCurrentUser() in a variable for much time. If you keep the value in a variable, and then the SDK updates the authentication state in the background, your code may not be looking at the correct value for firebaseAuth.getCurrentUser() anymore.

That’s why you’ll see more calls to firebaseAuth.getCurrentUser() than you might expect, and also why you’ll see firebaseAuth.addAuthStateListener in places that want to get notified when the authentication state changed, like when the user is signed in or out by the SDK.

Advertisement