首先,我是android编程的新手,对Facebook登录集成没有任何经验。而且我知道我应该在这些站点上发布这些问题,但是我只需要帮助...
我在Facebook登录集成方面遇到了一些问题,我已经完成了Google和Firebase身份验证,但这看起来很奇怪,因为这两个彼此相似...
我遇到的问题包括: 1. Facebook由于某种原因不会让我从他们的数据库中读取任何内容。在我的AccountInfoActivity活动中,我试图显示已登录用户的电子邮件。使用firebase和Google集成登录非常容易,但是我不知道为什么graphAPI不允许我这样做...
我想将内容保存到Firebase数据库中,以便系统自动检测用户是否已在线订购商品(因为我的应用程序是在线订购应用程序),但是由于问题1,我无法做到这一点。
在AccountInfoAcctivity活动中,我使程序检查是否已经登录了allready,因此界面知道它是否应显示“登录/注册”按钮。而且不管它只是什么都不会更改UI(重要说明:如果您在登录后退出应用程序并再次输入,它的确显示您已登录,但显示您所登录电子邮件的文本视图只是空白)
我制作了一个注销按钮,用于注销用户,该按钮仅在您使用Google和firebase Auth登录时才有效,但是在使用Facebook登录时却无法使用...
我已经尽我所能并做了测试,但是14岁那年我只知道那么多...而沮丧的我以为我会退后一步,向社区寻求帮助...
在我的LogInOrSignUpActivity中:
package com.brandshopping.brandshopping;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
import java.util.HashMap;
public class LoginOrSignupActivity extends AppCompatActivity {
private Button LoginBtn, RegisterWithEmailBtn, RegisterWithGoogleBtn;
private String Tag;
private ProgressDialog LoadingBar;
private LoginButton RegisterWithFacebookBtn;
private FirebaseDatabase firebasedatabase = FirebaseDatabase.getInstance();
private DatabaseReference database = firebasedatabase.getReference();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_or_signup);
LoadinGUI(); //LOAD IN THE GRAPHICAL USER INTERFACE
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
LoginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(LoginOrSignupActivity.this, LogInActivity.class));
}
});
RegisterWithEmailBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(LoginOrSignupActivity.this, RegisterActivity.class));
}
});
RegisterWithGoogleBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signIn(); //SIGN IN WITH GOOGLE
}
});
RegisterWithFacebookBtn.setOnClickListener(new View.OnClickListener() { //REGISTRATION WITH FACEBOOK
@Override
public void onClick(View view) {
SignInWithFacebook();
}
});
}
private void SignInWithFacebook(){
CallbackManager callbackManager = CallbackManager.Factory.create();
RegisterWithFacebookBtn.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Toast.makeText(LoginOrSignupActivity.this, "First part succeded", Toast.LENGTH_SHORT).show();
}
@Override
public void onCancel() {
Toast.makeText(LoginOrSignupActivity.this, "First part failed", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(FacebookException error) {
Toast.makeText(LoginOrSignupActivity.this, "First part failed", Toast.LENGTH_SHORT).show();
}
});
AccessTokenTracker TokenTracker = new AccessTokenTracker() {
@Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
if (currentAccessToken == null){
Toast.makeText(LoginOrSignupActivity.this, "User logged out", Toast.LENGTH_SHORT).show();
}else{
LoadInUserInfo(currentAccessToken);
}
}
};
AccessToken accessToken = AccessToken.getCurrentAccessToken();
}
private void LoadInUserInfo(AccessToken newaccesstoken){ //GET USER INFO FROM FACEBOOK, FOR FACEBOOK LOGIN
GraphRequest request = GraphRequest.newMeRequest(newaccesstoken, new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String facebook_first_name = object.getString("first_name");
String facebook_last_name = object.getString("last_name");
String facebook_email = object.getString("email");
String facebook_id = object.getString("id");
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(LoginOrSignupActivity.this, "Retrieving info failed", Toast.LENGTH_SHORT).show();
}
}
});
Bundle parameters = new Bundle();//REQUEST PARAMETERS FOR PERMISSIONS
parameters.putString("fields", "first_name, last_name, email, id");
request.setParameters(parameters);
request.executeAsync();
}
private void signIn() { //Google sign in
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) //google object
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(LoginOrSignupActivity.this, gso); //Create Google sign in object
//GOOGLE OBJECT
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, 1);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { //STARTACTIVITYFORRESULT, 1 = GOOGLE, 2 = FACEBOOK INTEGRATED LOGIN
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == 1) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}else{
CallbackManager callbackManager = CallbackManager.Factory.create(); //Create a callbackmaneger (register for facebook) object
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) { //HANDLE SIGN IN RESULTS / VALIDATE ACCOUNT INFO
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
Toast.makeText(this, "Register/signin successful", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginOrSignupActivity.this, AccountInfoActivity.class));
firebaseAuthWithGoogle(account);
SaveToDataBase();
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Toast.makeText(this, "Log in failed", Toast.LENGTH_SHORT).show();
Log.e(Tag, "error: ");
startActivity(new Intent(LoginOrSignupActivity.this, AccountInfoActivity.class));
}
}
void SaveToDataBase() { //SAVE TO THE FIREBASE REALTIME DATABASE
database.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
GoogleSignInAccount Guser = GoogleSignIn.getLastSignedInAccount(LoginOrSignupActivity.this);
String EmailWithEtheraRemoved = Guser.getEmail().replace(".", " ");
if (!(dataSnapshot.child("Users").child(EmailWithEtheraRemoved).exists())) {
LoadingBar.setMessage("Please wait while we load the credentialls in");
LoadingBar.setTitle("Register");
LoadingBar.setCanceledOnTouchOutside(false);
LoadingBar.show();
HashMap<String, Object> Userdatamap = new HashMap<>();
Userdatamap
.put("Email", Guser.getEmail());
Userdatamap
.put("Phone number", "Google intigrated sign in does not allow phone number requesting... This will be fixed in later patches");
Userdatamap
.put("Name", Guser.getGivenName() + Guser.getFamilyName());
if (Guser != null) {
Userdatamap
.put("Created with", "Intigrated Google sign in");
}
database
.child("Users")
.child(EmailWithEtheraRemoved)
.updateChildren(Userdatamap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
LoadingBar.dismiss();
Toast.makeText(LoginOrSignupActivity.this, "Database save successful", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginOrSignupActivity.this, AccountInfoActivity.class));
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(LoginOrSignupActivity.this, "Registration failed", Toast.LENGTH_SHORT).show();
Log.e(Tag, "error: ");
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { //SAVE GOOGLE ACCOUNT INFO TO THE FIREBASE AUTHENTICATION DATABASE
Log.d("authenticate", "firebaseAuthWithGoogle:" + acct.getId());
final FirebaseAuth mAuth = FirebaseAuth.getInstance();
final GoogleSignInAccount Guser = GoogleSignIn.getLastSignedInAccount(LoginOrSignupActivity.this);
AuthCredential credential =
GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>()
{
@Override
public void onComplete(@NonNull Task<AuthResult> task)
{
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d("message","signInWithCredential:success");
Log.d("user id", Guser.getId());
} else {
// If sign in fails, display a message to the user.
Log.w("message","signInWithCredential:failure", task.getException());
}
}
});
}
private void LoadinGUI() { //CREATE ALL OBJECTS FOR THE GRAPHICAL USER INTERFACE (GUI)
CallbackManager callbackManager = CallbackManager.Factory.create(); //NEEDED FOR FACEBOOK LOGIN
final String EMAIL = "email";
LoadingBar = new ProgressDialog(LoginOrSignupActivity.this);
LoginBtn = (Button) findViewById(R.id.Login_btn);
RegisterWithEmailBtn = (Button) findViewById(R.id.Register_WithEmail_btn);
RegisterWithGoogleBtn = (Button) findViewById(R.id.Register_WithGoogle_btn);
RegisterWithFacebookBtn = (LoginButton) findViewById(R.id.Register_WithFacebook_btn);
RegisterWithFacebookBtn.setReadPermissions(Arrays.asList(EMAIL)); //ADD PERMISSIONS, HAVE TO ADD TO BE ABLE TO READ THINGS
}
}
在我的AccountInfoActivity类中(最重要的一个):
package com.brandshopping.brandshopping;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.sip.SipSession;
import android.os.Bundle;
import android.text.Layout;
import android.text.style.UpdateLayout;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.internal.ImageRequest;
import com.facebook.login.LoginManager;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInApi;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import org.json.JSONException;
import org.json.JSONObject;
public class AccountInfoActivity extends AppCompatActivity {
private FirebaseDatabase firebasedatabase = FirebaseDatabase.getInstance();
private DatabaseReference RootRef = firebasedatabase.getReference();
private DatabaseReference Users = RootRef.child("Users");
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser user = firebaseAuth.getCurrentUser();
private ImageView trending_icon, product_icon, cart_icon;
private Button register_btn;
private CardView cardView;
private TextView logout_btn, logged_in_as_email;
private String Facebook_email;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account_info);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
final GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
LoadInGUI();
LoadInOnClickListener();
register_btn
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(AccountInfoActivity.this, LoginOrSignupActivity.class));
}
});
logout_btn
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
mGoogleSignInClient.signOut();
LoginManager.getInstance().logOut();
startActivity(new Intent(AccountInfoActivity.this, AccountInfoActivity.class));
}
});
AccessTokenTracker TokenTracker = new AccessTokenTracker() {
@Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
if (currentAccessToken == null) {
Toast.makeText(AccountInfoActivity.this, "User logged out", Toast.LENGTH_SHORT).show();
} else {
FacebookSdk.sdkInitialize(getApplicationContext());
LoadInUserInfo(currentAccessToken);
}
}
};
AccessToken accessToken = AccessToken.getCurrentAccessToken();
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(AccountInfoActivity.this);
if(user != null || account != null || accessToken != null){
ChangeUi();
}
}
private void LoadInUserInfo(AccessToken newaccesstoken){ //GET USER INFO FROM FACEBOOK, FOR FACEBOOK LOGIN
GraphRequest request = GraphRequest.newMeRequest(newaccesstoken, new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String facebook_email = object.getString("email");
Facebook_email = facebook_email;
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();//REQUEST PARAMETERS FOR PERMISSIONS
parameters.putString("fields", "email");
request.setParameters(parameters);
request.executeAsync();
}
public void ChangeUi() {
//FOR FACEBOOK RETRIEVING DATA
AccessToken accessToken = AccessToken.getCurrentAccessToken();
//------------------------------------
register_btn
.setVisibility(View.INVISIBLE);
cardView
.setVisibility(View. VISIBLE);
logout_btn
.setVisibility(View. VISIBLE);
//------------------------------------
FirebaseUser Euser = FirebaseAuth.getInstance().getCurrentUser();
GoogleSignInAccount Guser = GoogleSignIn.getLastSignedInAccount(AccountInfoActivity.this);
//------------------------------------
if (Euser != null) {
logged_in_as_email.setText(Euser.getEmail());
}else if (Guser != null) {
logged_in_as_email.setText(Guser.getEmail());
}else if (accessToken != null){
logged_in_as_email.setText(Facebook_email);
}
}
private void LoadInOnClickListener() {
product_icon
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(AccountInfoActivity.this, ProductViewActivity.class));
overridePendingTransition(0, 0);
}
});
trending_icon
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(AccountInfoActivity.this, MainActivity.class));
overridePendingTransition(0, 0);
}
});
cart_icon
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(AccountInfoActivity.this, CartActivity.class));
overridePendingTransition(0, 0);
}
});
}
@Override
protected void onPause() {
super.onPause();
overridePendingTransition(0, 0); //disable animation when pressing back button
}
private void LoadInGUI() {
trending_icon = (ImageView) findViewById(R.id.TrendingIcon);
product_icon = (ImageView) findViewById(R.id.ProductIcon);
cart_icon = (ImageView) findViewById(R.id.CartIcon);
register_btn = (Button) findViewById(R. id. Register_btn);
cardView = (CardView) findViewById(R. id. CardView1);
logout_btn = (TextView) findViewById(R. id. Logout_textview_btn);
logged_in_as_email = (TextView) findViewById(R. id. Logged_in_as_email);
}
}
任何帮助都将不胜感激