4

ContexteLa combinaison de Facebook et Google auth pour Firebase Android

Bonjour, je suis nouveau avec Firebase pour Android et je suis en train de mettre en œuvre le Facebook et Google auth/connexion pour la première fois. J'ai suivi ces deux tutoriels pour l'authentification correspondante:

  • http: // firebase.google.com/docs/auth/android/google-signin
  • http: // firebase.google.com/docs/ auth/android/facebook-login

Par ailleurs, le FacebookSignInActivity et GoogleSignInActivity fonctionnent comme ils le devraient.

Problème

Le problème est que je suis en train d'utiliser le auth Google et Facebook dans la même activité, mais il ne fonctionnera pas. Comme si:

result layout image

Ce que j'ai

J'ai essayé de garder le FacebookSignInActivity séparé du GoogleSignInActivity en les laissant étendre un MainActivity et définir la mise en page là-dedans.

Mais je pense que je suis supposé fusionner les deux en un. Alors j'ai essayé, mais je reçois une étrange exception NullPointer:

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.firebase.auth.FirebaseAuth.addAuthStateListener(com.google.firebase.auth.FirebaseAuth$AuthStateListener)' on a null object reference 

Je ne sais pas pourquoi l'objet est nul dans le onCreate parce que je l'ai copié le même code des deux autres activités qui travaillent :

mAuth = FirebaseAuth.getInstance(); 

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"); 
       } 
       // [START_EXCLUDE] 
       updateUI(user); 
       // [END_EXCLUDE] 
      } 
     }; 

Je ne suis même pas sûr si je suis même supposé fusionner les deux en une seule activité. J'ai aussi vérifié ces liens:

Mais il semble que c'est quelque chose d'autre de ce que je suis en train de faire. Si quelqu'un pouvait m'aider dans la bonne direction, il serait volontiers apprécié.

+1

Le code que vous avez publié n'est pas le code lançant l'exception. L'exception se produit lorsque vous appelez 'mAuth.addAuthStateListener (mAuthListener)' et 'mAuth' est null. Confirmez que vous avez exécuté 'mAuth = FirebaseAuth.getInstance()', avant d'essayer d'ajouter l'écouteur. –

+0

Comme dans les tutoriels de la base de données Firebase, la ligne à laquelle vous faites référence: 'mAuth = FirebaseAuth.getInstance()' est dans mon fragment de code. Il est appelé dans onCreate. Le 'mAuth.addAuthStateListener (mAuthListener);' est appelé dans le onStart. – Tim

Répondre

4

Vous pouvez essayer ce code:

public class LoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, 
     View.OnClickListener { 

    private static final String TAG = "SignInActivity"; 
    private static final int RC_SIGN_IN = 9001; 

    private GoogleApiClient mGoogleApiClient; 
    private FirebaseAuth mAuth; 
    private FirebaseAuth.AuthStateListener mAuthListener; 

    private CallbackManager mCallbackManager; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.activity_login); 

     // Facebook Login 
     FacebookSdk.sdkInitialize(getApplicationContext()); 
     mCallbackManager = CallbackManager.Factory.create(); 

     LoginButton mFacebookSignInButton = (LoginButton) findViewById(R.id.facebook_button); 
     mFacebookSignInButton.setReadPermissions("email", "public_profile", "user_birthday", "user_friends"); 

     mFacebookSignInButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() { 
      @Override 
      public void onSuccess(LoginResult loginResult) { 
       Log.d(TAG, "facebook:onSuccess:" + loginResult); 
       firebaseAuthWithFacebook(loginResult.getAccessToken()); 
      } 

      @Override 
      public void onCancel() { 
       Log.d(TAG, "facebook:onCancel"); 
      } 

      @Override 
      public void onError(FacebookException error) { 
       Log.d(TAG, "facebook:onError", error); 
      } 
     }); 

     // Google Sign-In 
     // Assign fields 
     Button mGoogleSignInButton = (Button) findViewById(R.id.google_button); 

     // Set click listeners 
     mGoogleSignInButton.setOnClickListener(this); 

     GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 
       .requestIdToken(getString(R.string.default_web_client_id)) 
       .requestEmail() 
       .build(); 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */) 
       .addApi(Auth.GOOGLE_SIGN_IN_API, gso) 
       .build(); 

     // Initialize FirebaseAuth 
     mAuth = FirebaseAuth.getInstance(); 

     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"); 
       } 
      } 
     }; 
    } 

    @Override 
    public void onStart() { 
     super.onStart(); 
     mAuth.addAuthStateListener(mAuthListener); 
    } 

    @Override 
    public void onStop() { 
     super.onStop(); 
     if (mAuthListener != null) { 
      mAuth.removeAuthStateListener(mAuthListener); 
     } 
    } 

    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { 
     Log.d(TAG, "firebaseAuthWithGooogle:" + acct.getId()); 
     AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); 
     mAuth.signInWithCredential(credential) 
       .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { 
        @Override 
        public void onComplete(@NonNull Task<AuthResult> task) { 
         Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful()); 

         // If sign in fails, display a message to the user. 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. 
         if (!task.isSuccessful()) { 
          Log.w(TAG, "signInWithCredential", task.getException()); 
          Toast.makeText(LoginActivity.this, "Authentication failed.", 
            Toast.LENGTH_SHORT).show(); 
         } else { 
          startActivity(new Intent(LoginActivity.this, MainActivity.class)); 
          finish(); 
         } 
        } 
       }); 
    } 

    private void firebaseAuthWithFacebook(AccessToken token) { 
     Log.d(TAG, "handleFacebookAccessToken:" + token); 

     final AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken()); 
     mAuth.signInWithCredential(credential) 
       .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { 
        @Override 
        public void onComplete(@NonNull Task<AuthResult> task) { 
         Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful()); 

         // If sign in fails, display a message to the user. 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. 
         if (!task.isSuccessful()) { 
          Log.w(TAG, "signInWithCredential", task.getException()); 
          Toast.makeText(LoginActivity.this, "Authentication failed.", 
            Toast.LENGTH_SHORT).show(); 
         } else { 
          startActivity(new Intent(LoginActivity.this, MainActivity.class)); 
          finish(); 
         } 
        } 
       }); 
    } 

@Override 
    public void onClick(View v) { 
     switch (v.getId()) { 
      case R.id.google_button: 
       signIn(); 
       break; 
      default: 
       return; 
     } 
    } 

    private void signIn() { 
     Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); 
     startActivityForResult(signInIntent, RC_SIGN_IN); 
    } 
    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 

     mCallbackManager.onActivityResult(requestCode, resultCode, data); 

     // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); 
     if (requestCode == RC_SIGN_IN) { 
      GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); 
      if (result.isSuccess()) { 
       // Google Sign In was successful, authenticate with Firebase 
       GoogleSignInAccount account = result.getSignInAccount(); 
       firebaseAuthWithGoogle(account); 
      } else { 
       // Google Sign In failed 
       Log.e(TAG, "Google Sign In failed."); 
      } 
     } 
    } 

    @Override 
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 
     // An unresolvable error has occurred and Google APIs (including Sign-In) will not 
     // be available. 
     Log.d(TAG, "onConnectionFailed:" + connectionResult); 
     Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show(); 
    } 

} 

S'il vous plaît laissez-moi savoir si vous avez des questions.

0

Peut-être que ceux qui cherchent encore une solution:

En activité (yourLoginActivity.classe)

* Créer un int constant représente la requestCode pour ActivityForResult

// You can change to any Value just be unique 
    private static final int RC_SIGN_IN = 1001; 

-> déclarer GoogleApiClient, FirebaseAuth, AuthStateListener et CallbackManager

private static final String TAG = "LoginActivity"; 
private static final int RC_SIGN_IN = 1001; 
private GoogleApiClient mGoogleApiClient; 
private FirebaseAuth mAuth; 
private FirebaseAuth.AuthStateListener mAuthListener; 
private CallbackManager mCallbackManager; 

-> Initialiser les variables déclarées ci-dessus:

mCallbackManager = CallbackManager.Factory.create(); mAuth = FirebaseAuth.getInstance(); 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"); 
     } 
    } }; 

-> Faire référence à Si ngInButton et LoginButton:

LoginButton facebookLoginButton = findViewById(R.id.login_facebook_button); 
    SignInButton mGoogleSignInButton = findViewById(R.id.sign_in_button); 

-> Manipulez le SingInButton et LoginButton:

facebookLoginButton.setReadPermissions("email", "public_profile", "user_birthday"); 
facebookLoginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() { 
    @Override 
    public void onSuccess(LoginResult loginResult) { 
     firebaseAuthWithFacebook(loginResult.getAccessToken()); 
    } 

    @Override 
    public void onCancel() { 
     Toast.makeText(LoginActivity.this, "Succes", Toast.LENGTH_SHORT).show(); 
    } 

    @Override 
    public void onError(FacebookException error) { 
     Toast.makeText(LoginActivity.this, "Succes", Toast.LENGTH_SHORT).show(); 
    } 
}); 

mGoogleSignInButton.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View view) { 
     signIn(); 
    } 
}); 

-> Gérer les GoogleSingInOptions et GoogleApiClient

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 
     .requestIdToken(getString(R.string.default_web_client_id)) 
     .requestEmail() 
     .build(); 

mGoogleApiClient = new GoogleApiClient.Builder(this) 
     .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */) 
     .addApi(Auth.GOOGLE_SIGN_IN_API, gso) 
     .build(); 

-> Manipulez le Facebook Connectez-vous

private void authWithFacebook(AccessToken token) { 
    Log.d(TAG, "handleFacebookAccessToken:" + token); 
    final AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken()); 
    if (mAuth.getCurrentUser() != null) { 
     mAuth.getCurrentUser().linkWithCredential(credential) 
       .addOnSuccessListener(new OnSuccessListener<AuthResult>() { 
      @Override 
      public void onSuccess(AuthResult authResult) { 
       Toast.makeText(LoginActivity.this, "Logged IN", Toast.LENGTH_LONG).show(); 
      } 
     }) 

       .addOnFailureListener(new OnFailureListener() { 
        @Override 
        public void onFailure(@NonNull Exception e) { 
         e.printStackTrace(); 
         Log.e(TAG, "onFailure: " + e.getMessage()); 
         mAuth.signInWithCredential(credential).addOnSuccessListener(new OnSuccessListener<AuthResult>() { 
          @Override 
          public void onSuccess(AuthResult authResult) { 
           Toast.makeText(LoginActivity.this, "Logged IN", Toast.LENGTH_LONG).show(); 
          } 
         }); 
        } 
       }); 
    } else { 
     mAuth.signInWithCredential(credential); 
    } 
} 

-> Manipulez le login Google:

pprivate void authWithGoogle(final GoogleSignInAccount acct) { 
    Log.d(TAG, "firebaseAuthWithGooogle:" + acct.getId()); 
    final AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); 
    if (mAuth.getCurrentUser() != null) { 
     mAuth.getCurrentUser().linkWithCredential(credential).addOnSuccessListener(new OnSuccessListener<AuthResult>() { 
      @Override 
      public void onSuccess(AuthResult authResult) { 
       Toast.makeText(LoginActivity.this, "Logged IN", Toast.LENGTH_LONG).show(); 
      } 
     }) 

       .addOnFailureListener(new OnFailureListener() { 
        @Override 
        public void onFailure(@NonNull Exception e) { 
         e.printStackTrace(); 
         Log.e(TAG, "onFailure: " + e.getMessage()); 
         mAuth.signInWithCredential(credential).addOnSuccessListener(new OnSuccessListener<AuthResult>() { 
          @Override 
          public void onSuccess(AuthResult authResult) { 
           Toast.makeText(LoginActivity.this, "Logged IN", Toast.LENGTH_LONG).show(); 
          } 
         }); 
        } 
       }); 
    }else{ 
     mAuth.signInWithCredential(credential); 
    } 
} 

-> surchargent onConnectionFailed():

@Override 
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 
    // An unresolvable error has occurred and Google APIs (including Sign-In) will not 
    // be available. 
    Log.d(TAG, "onConnectionFailed:" + connectionResult); 
    Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show(); 
} 

-> Chant et appelant le onActivityForResult()

private void signIn() { 
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); 
    startActivityForResult(signInIntent, RC_SIGN_IN); 
} 

-> Mettre en œuvre GoogleApiClient.OnConnectionFailedListener

LoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener{ 
.... 
} 

Assurez-vous d'avoir ACTIVÉ FACEBOOK SDK Connectez-vous DEPUIS LA CONSOLE DE FIREBASE ET INSTALLEZ CORRECTEMENT!