PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 2, 2022

[FIXED] why my currentUser is always null if I login using facebook in firebase authentication?

 November 02, 2022     android, facebook, firebase, firebase-authentication, kotlin     No comments   

Issue

in login page, I use these 2 codes below:

    facebookLoginButton.setOnClickListener {
          facebookLoginManager.logInWithReadPermissions(this, Arrays.asList("email", "public_profile"))
    }

    private fun setUpFacebookLogin() {

        facebookLoginManager.registerCallback(callbackManager, object : FacebookCallback<LoginResult> {

            override fun onSuccess(loginResult: LoginResult) {
                Log.d(TAG, "facebook:onSuccess:$loginResult")
                handleFacebookAccessToken(loginResult.accessToken)
            }

            override fun onCancel() {
                Log.d(TAG, "facebook:onCancel")
                progressBar.visibility = View.GONE

            }

            override fun onError(error: FacebookException) {
                Log.d(TAG, "facebook:onError", error)
                progressBar.visibility = View.GONE
                mActivity.longToast("Gagal masuk dengan akun Facebook, silahkan periksa koneksi internet Anda, atau gunakan akun Google atau email yang lain.")

            }
        })

    }

    private fun handleFacebookAccessToken(token: AccessToken) {

        Log.d(TAG, "handleFacebookAccessToken:$token")

        val credential = FacebookAuthProvider.getCredential(token.token)

        auth.signInWithCredential(credential).addOnSuccessListener {

            Log.d(TAG, "facebook signInWithCredential:success")

            val user = auth.currentUser ?: return@addOnSuccessListener
            checkUserBasicDataInFirestore(user)

        }.addOnFailureListener {exception ->

            progressBar.visibility = View.GONE
            Log.d(TAG, "facebook signInWithCredential failed: ${exception.localizedMessage}")
            mActivity.longToast(exception.localizedMessage)
        }


    }

I actually can register the user to firebase auth by using those code, but I have problem when trying to login using facebook. auth.signInWithCredential(credential).addOnSuccessListener is triggered actually, so I assume I can success login using facebook in login page

but in the other screen (fragment), when I want to access the current user to get the uid, it always null, like this

val userFirebaseAuth = FirebaseAuth.getInstance().currentUser

I don't understand why userFirebaseAuth is always null ?


Solution

From my experience, the current user isn't always immediately available at the app launches from a cold start. It can take a moment for Firebase Authentication to initialize and refresh the user's ID token if necessary. Since you don't know how long that will take, you should use a listener to determine the first possible moment when the current user is absolutely known and verified by the SDK. It's a good idea to read about: How does the firebase AuthStateListener work?

Create a new AuthStateListener:

mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // Sign in logic here.
            }
        }
    };

Then add and remove it as needed:

FirebaseAuth.getInstance().addAuthStateListener(mAuthListener);
FirebaseAuth.getInstance().removeAuthStateListener(mAuthListener);

Also check out the API documentation on AuthStateListener.



Answered By - Doug Stevenson
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing