Order of execution auth. Firebase

advertisements

I'm trying to login with firebase authentication with facebook sdk and "user/password" options in android. I need to know what kind of authentication the user has used before start MainActivity.

Days ago the code used to work fine, but I had to erase the firebase project. Today I configured the firebase/facebook sdk and it works. But now the order of execution of the code is different (I know is very weird).

Before, onComplete method (when I validate if the task is successful) is executed first and then onAuthStateChanged. But now first onAuthStateChanged method is executed first, start the other activity and then validate if the task is successful. I see that behavior in debug mode.

here is the code example and I am grateful in advance for any help

fbLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            //Inicio de sesion con facebook exitoso
            handleFacebookAccessToken(loginResult.getAccessToken());
        }

        @Override
        public void onCancel() {
            //Inicio de sesion con facebook cancelado
            Toast.makeText(getApplicationContext(),R.string.cancel_fb_log,Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(FacebookException error) {
            //Inicio de sesion con facebook erroneo
            Toast.makeText(getApplicationContext(),R.string.error_fb_log,Toast.LENGTH_SHORT).show();
        }
    });

private void handleFacebookAccessToken(AccessToken accessToken) {
    relativeLayout.setVisibility(View.GONE);
    relativeLayout1.setVisibility(View.VISIBLE);
    AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken());
    //Iniciar sesión con una credencial
    firebaseAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        //metodo que se ejecuta al terminar el proceso
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (!task.isSuccessful()){
                //Ocurrio un error al realizar el logueo a firebase con facebook
                Utilities.exceptionFirebaseAdministrator(LoginActivity.this, task, LOG_TAG);
                LoginManager.getInstance().logOut();
            }else{
                pref.edit().putBoolean(getString(R.string.pref_logged_with_facebook),true).apply();
                pref.edit().putBoolean(getString(R.string.pref_logged_with_firebase),false).apply();
            }
            relativeLayout.setVisibility(View.VISIBLE);
            relativeLayout1.setVisibility(View.GONE);
        }
    });
}

fireAuthStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();

            if(user != null){

//I try use SharedPreference and validate if is facebook login or other
                    startMainActivity();

            }

        }
    };

@Override
public void onStart() {
    super.onStart();
    //Cuando la clase empieza a "escuchar"
    firebaseAuth.addAuthStateListener(fireAuthStateListener);
}

@Override
public void onStop() {
    super.onStop();
    //Cuando la clase deja de "escuchar"
    firebaseAuth.removeAuthStateListener(fireAuthStateListener);
}


Do this changes in your code ,

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
        // this is the login layout change it to yours.
    setContentView(R.layout.activity_login);

    // START initialize_auth
    mAuth = FirebaseAuth.getInstance();
    // START auth_state_listener
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
              //check if user is  not null
            if (user != null) {

// below code will triggers as soon as your facebook login task is successful                   

      // this will return provider as facebook,google,twitter,email ,etc

                String provider = user.getProviders().get(0) ;

                  pref.edit().putBoolean(getString(R.string.pref_logged_with_facebook), true).apply();
                  pref.edit().putBoolean(getString(R.string.pref_logged_with_firebase), false).apply();
  //I try use SharedPreference and validate if is facebook login or other
                startMainActivity();

            } else {
                // User is signed out
                Log.d(LOG_TAG, "user signed_out");
                // logout user and open login page .
            }
        }
    };

}

// [START on_start_add_listener]
@Override
public void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);
}

// [START on_stop_remove_listener]
@Override
public void onStop() {
    super.onStop();
    if (mAuthListener != null) {
        mAuth.removeAuthStateListener(mAuthListener);
    }
}

private void handleFacebookAccessToken(AccessToken accessToken) {
    relativeLayout.setVisibility(View.GONE);
    relativeLayout1.setVisibility(View.VISIBLE);
    AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken());
    //Iniciar sesión con una credencial
    firebaseAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
        //metodo que se ejecuta al terminar el proceso
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (!task.isSuccessful()) {

                // If sign in fails, log message or go back to login page.
                //If sign in succeeds the auth state listener will be
               //notified and logic to handle the
              // signed in user can be handled in the listener.

                Utilities.exceptionFirebaseAdministrator(LoginActivity.this, task, LOG_TAG);
                LoginManager.getInstance().logOut();
            }
              // this will execute no matter whats happens ,
            relativeLayout.setVisibility(View.VISIBLE);
            relativeLayout1.setVisibility(View.GONE);
        }
    });
}

}