Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with FirebaseAuth inside Android Module

I am developing a Chat library in which I want to show the conversations of the logged in user. The reason to make the library is that I want to integrate it in multiple projects.

The problem I am facing right now is that FirebaseAuth is indicating that the user is not logged-in (FirebaseAuth.getInstance(mFirebaseApp).getCurrentUser() always returning null) even if the user is authenticated inside the app.

How the Module/Library can know that the user is authenticated?

I am trying the following code:

mAPIKey = getArguments().getString(ConversationModuleConstants.API_KEY_KEY);
        mApplicatoinId = getArguments().getString(ConversationModuleConstants.APPLICATION_ID_KEY);
        mDatabaseUrl = getArguments().getString(ConversationModuleConstants.DATABASE_URL_KEY);

        FirebaseOptions options = new FirebaseOptions.Builder()
                .setApiKey(mAPIKey)
                .setApplicationId(mApplicatoinId)
                .setDatabaseUrl(mDatabaseUrl)
                .build();

        boolean hasBeenInitialized = false;
        List<FirebaseApp> firebaseApps = FirebaseApp.getApps(getActivity());
        for (FirebaseApp app : firebaseApps) {
            if (app.getName().equals(FIREBASE_APP_NAME)) {
                hasBeenInitialized = true;
                mFirebaseApp = app;
            }
        }

        if (!hasBeenInitialized) {
            mFirebaseApp = FirebaseApp.initializeApp(getActivity(), options, FIREBASE_APP_NAME);
        }

 if (FirebaseAuth.getInstance(mFirebaseApp).getCurrentUser() == null) {
            Toast.makeText(getActivity(), "Login Required!", Toast.LENGTH_SHORT).show();
            return;
        }
like image 566
Shajeel Afzal Avatar asked Jun 10 '26 22:06

Shajeel Afzal


1 Answers

You need to add a listener/Observer to get the userid for every auth state change.

FirebaseAuth.getInstance().addAuthStateListener(firebaseAuth -> {
            if (firebaseAuth.getCurrentUser() == null) {
                your code goes here
            }
        });

https://firebase.google.com/docs/auth/android/manage-users

Another method wkile login get the user id and store in LocalStorage, while logout clear the localstorage, so that you will be able to maintain in offline too.

like image 150
Prags Avatar answered Jun 13 '26 10:06

Prags



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!