背景
您好,我是Firebase for Android的新手,我是第一次尝试实施Facebook和Google身份验证/登录。我按照这两个教程进行了相应的身份验证:
另外,FacebookSignInActivity
和GoogleSignInActivity
正在按预期工作。
问题
问题在于我尝试在同一活动中使用Google和Facebook身份验证,但它不会起作用。像这样:
我做了什么
我试图让FacebookSignInActivity
与GoogleSignInActivity
分开,让他们扩展MainActivity
并在那里设置布局。
但我认为我应该把这两者合二为一。所以我试过了,但我得到了一个奇怪的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
我不知道为什么onCreate
中的对象为空,因为我已经从正在运行的其他两个活动中复制了相同的代码:
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]
}
};
我甚至不确定我是否应该将这两者合并为一个活动。我还检查了这些链接:
但看起来这是我试图做的事情。如果有人可以帮助我指出正确的方向,我们将很高兴地感激。
答案 0 :(得分:5)
您可以尝试以下代码:
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();
}
}
如果您有任何疑问,请与我们联系。
答案 1 :(得分:0)
也许还有人在寻找解决方案:
在活动中(yourLoginActivity.class)
*创建一个常量int来表示ActivityForResult
的requestCodeadd_action( 'woocommerce_admin_order_data_after_shipping_address', 'admin_custom_row_after_order_addresses', 10, 1 );
function admin_custom_row_after_order_addresses( $order ){
?>
</div></div>
<div class="clear"></div>
<!-- new custom section row -->
<div class="order_data_column_container">
<div class="order_data_column_wide">
<h3><?php _e("My Custom row title"); ?></h3>
<!-- custom row paragraph -->
<p><?php
_e("Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.");
?></p>
<?php
}
- &GT;声明GoogleApiClient,FirebaseAuth,AuthStateListener和CallbackManager
// You can change to any Value just be unique
private static final int RC_SIGN_IN = 1001;
- &GT;初始化上面声明的变量:
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;
- &GT;参考SingInButton和LoginButton:
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");
}
} };
- &GT;处理SingInButton和LoginButton:
LoginButton facebookLoginButton = findViewById(R.id.login_facebook_button);
SignInButton mGoogleSignInButton = findViewById(R.id.sign_in_button);
- &GT;管理GoogleSingInOptions和GoogleApiClient
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();
}
});
- &GT;处理Facebook登录
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();
- &GT;处理谷歌登录:
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);
}
}
- &GT;覆盖onConnectionFailed():
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);
}
}
- &GT;唱歌并调用onActivityForResult()
@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();
}
- &GT;实施GoogleApiClient.OnConnectionFailedListener
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
请确保您已 已启用FACEBOOK SDK 从FIREBASE控制台登录并正确设置!
答案 2 :(得分:0)
有人想在Kotlin中做到这一点
class LoginFragment(): Fragment() , GoogleApiClient.OnConnectionFailedListener {
override fun onConnectionFailed(p0: ConnectionResult) {
Toast.makeText(activity, "Google Play Services error.", Toast.LENGTH_SHORT).show();
}
private val TAG = "SignInActivity"
private val RC_SIGN_IN = 9001
private var mGoogleApiClient: GoogleApiClient? = null
private var mAuth: FirebaseAuth? = null
private var mAuthListener: FirebaseAuth.AuthStateListener? = null
private var mCallbackManager: CallbackManager? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.likes_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
FacebookSdk.sdkInitialize(activity);
mCallbackManager = CallbackManager.Factory.create()
google_container.setOnClickListener {
signIn()
}
// Facebook Button (LoginButton) from xml
login_button.setReadPermissions("email", "public_profile")
login_button.fragment = this
login_button.run {
registerCallback(mCallbackManager, object: FacebookCallback<LoginResult> {
override fun onSuccess(result: LoginResult?) {
Log.e(TAG, "Succesfull Facebook Sign In")
firebaseAuthWithFacebook(result?.accessToken!!)
}
override fun onCancel() {
Log.e(TAG, "Cancelled Facebook Sign In")
}
override fun onError(error: FacebookException?) {
Log.e(TAG, "Facebook sign in error : " + error.toString())
}
})
}
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
mGoogleApiClient = GoogleApiClient.Builder(activity!!.applicationContext)
.enableAutoManage(this.activity!! /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build()
mAuth = FirebaseAuth.getInstance()
mAuthListener = FirebaseAuth.AuthStateListener { firebaseAuth ->
val user = firebaseAuth.currentUser
if (user != null) {
// User is signed in
Log.e(TAG, "onAuthStateChanged:signed_in:" + user.uid)
} else {
// User is signed out
Log.e(TAG, "onAuthStateChanged:signed_out")
}
}
}
fun signIn() {
val signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient)
startActivityForResult(signInIntent, RC_SIGN_IN);
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
mCallbackManager!!.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
val result = Auth.GoogleSignInApi.getSignInResultFromIntent(data)
if (result.isSuccess) {
// Google Sign In was successful, authenticate with Firebase
val account = result.signInAccount
firebaseAuthWithGoogle(account!!)
} else {
// Google Sign In failed
Log.e(TAG, "Google Sign In failed.");
}
}
}
private fun firebaseAuthWithGoogle(token : GoogleSignInAccount) {
Log.e(TAG, "handleGoogleAccessToken:" + token);
val credential = GoogleAuthProvider.getCredential(token.idToken,null)
mAuth!!.signInWithCredential(credential)
.addOnCompleteListener(activity as MainActivity, object : OnCompleteListener<AuthResult> {
override fun onComplete(task: Task<AuthResult>) {
Log.e(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
if(!task.isSuccessful){
Toast.makeText(activity, "Failed", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(activity, "Success", Toast.LENGTH_SHORT).show();
}
}
})
}
private fun firebaseAuthWithFacebook(token : AccessToken) {
Log.e(TAG, "handleFacebookAccessToken:" + token);
val credential = FacebookAuthProvider.getCredential(token.token)
mAuth!!.signInWithCredential(credential)
.addOnCompleteListener(activity as MainActivity, object : OnCompleteListener<AuthResult> {
override fun onComplete(task: Task<AuthResult>) {
Log.e(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
if(!task.isSuccessful){
Toast.makeText(activity, "Failed", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(activity, "Success", Toast.LENGTH_SHORT).show();
}
}
})
}
}