I'm trying to login from Facebook and Google API, the Google API works fine, the problem arises with Facebook login, everything is setup on the Facebook developers console and my app is live as well.
The problem is whenever user clicks on the login button (which is a customized ImageButton) the ProgressBar shows up and then it goes away and the app is still on the same activity without user being logged in.
The complete code for that activity is:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_opening);
progressDialog = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
Auth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
GoogleSignInOptions gso = new GoogleSignInOptions
.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
Google = (ImageView) findViewById(R.id.googleSignin);
Google.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SIGN_IN_REQUEST = 1;
signIn();
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
});
callbackManager = CallbackManager.Factory.create();
Facebook = (ImageView) findViewById(R.id.facebookSignin);
Facebook.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SIGN_IN_REQUEST = 2;
progressDialog.show();
progressDialog.setCancelable(false);
progressDialog.setMessage("Loading...");
LoginManager.getInstance().logInWithReadPermissions(opening.this, Arrays.asList("email", "public_profile"));
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG2, "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
setFbData(loginResult);
progressDialog.dismiss();
}
@Override
public void onCancel() {
Log.d(TAG2, "facebook:onCancel");
Toast.makeText(getApplicationContext(),"facebook:oncancel",Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
@Override
public void onError(FacebookException error) {
Log.d(TAG2, "facebook:onError", error);
Toast.makeText(getApplicationContext(),"facebook:onError",Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
});
}
});
Email = (ImageView)findViewById(R.id.emailLogin);
Email.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), SignIn.class);
startActivity(intent);
finish();
}
});
AlreadyLoggedin = (ImageView)findViewById(R.id.Already);
AlreadyLoggedin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), login.class);
startActivity(intent);
finish();
}
});
}
private void signIn(){
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (SIGN_IN_REQUEST == 1) {
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
Toast.makeText(getApplicationContext(), "Google sign in Failed", Toast.LENGTH_LONG).show();
String s1 = task.getException().getMessage();
Toast.makeText(getApplicationContext(),"" + s1,Toast.LENGTH_LONG).show();
progressDialog.dismiss();
String s = task.getException().getMessage();
Toast.makeText(getApplicationContext(),"ErrorCode: " + s,Toast.LENGTH_LONG).show();
}
}
} else if (SIGN_IN_REQUEST == 2){
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + 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) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Snackbar.make(findViewById(R.id.snake), "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
progressDialog.dismiss();
updateUI(null);
}
// ...
}
});
}
@Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
}
private void updateUI(FirebaseUser user) {
/*
Intent intent = new Intent(opening.this, MainActivity.class);
startActivity(intent);
finish();
*/
progressDialog.dismiss();
if (SIGN_IN_REQUEST == 1) {
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
if (acct != null) {
String personName = acct.getDisplayName();
String personGivenName = acct.getGivenName();
String personFamilyName = acct.getFamilyName();
String personEmail = acct.getEmail();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();
String uid = mAuth.getCurrentUser().getUid();
Intent intent = new Intent(opening.this, userInf.class);
intent.putExtra("UID", uid);
intent.putExtra("Phone", PhoneNumber);
intent.putExtra("Name", personName);
startActivity(intent);
finish();
}
} else if (SIGN_IN_REQUEST == 2) {
if (user != null) {
progressDialog.dismiss();
Intent intent = new Intent(opening.this, userInf.class);
intent.putExtra("Phone", PhoneNumber);
intent.putExtra("Name", Name);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(),"updating error",Toast.LENGTH_LONG).show();
}
}
}
private void setFbData(final LoginResult loginResult){
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String first_name = response.getJSONObject().getString("first_name");
String last_name = response.getJSONObject().getString("last_name");
Name = String.valueOf(first_name + " " + last_name);
} catch (JSONException e){
e.printStackTrace();
}
}
});
}
private void handleFacebookAccessToken(AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
Toast.makeText(getApplicationContext(),"HandelingRequest",Toast.LENGTH_LONG).show();
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
Auth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
progressDialog.dismiss();
updateUI(user);
} else {
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(opening.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
updateUI(null);
}
}
});
}}
The log out is something like this:
D/FACELOG: facebook:onSuccess:com.facebook.login.LoginResult@d573369
D/GoogleActivity: handleFacebookAccessToken:{AccessToken token:ACCESS_TOKEN_REMOVED permissions:[public_profile, email]}
W/BiChannelGoogleApi: [FirebaseAuth: ] getGoogleApiForMethod() returned Gms: com.google.firebase.auth.api.internal.zzal@6703527
I/FirebaseAuth: [FirebaseAuth:] Loading module via FirebaseOptions.
[FirebaseAuth:] Preparing to create service connection to gms implementation
I've been looking around for this from quite some time and have not found anything which solves my problem.
Rule Out Third-Party Apps Developers of other third-party apps sometimes face confusion about the need to include the code for Facebook authentication. If you constantly experience the problem with just one app, consider contacting the developer for assistance. If you don’t use the app, uninstall it.
Authentication is the method by which Facebook determines that you are you and grants access to your account. Normally this error only emits if you enter the wrong email, password, or if Facebook detects other suspicious activity on your account.
Facebook needs an option where users can request the user's QR setup authentication code sent to the user's primary email address. With the QR code, it can be scanned on any authenication app and the 6 digit code would be displayed on the app.
To begin, you need to have a Facebook account. Then, go to pub.dev, get the flutter_facebook_login package, and add it to your pubspec.yaml. Now, this tutorial will be split in half, with one section for Android and another one for iOS. The main reason is that the installation of Facebook SDK will be different for both users.
I am using the following method for fb login, As per our knolwedge, we have tested all the boundary conditions & its working fine for us now and never faced any challenge yet.
//on click of fb button
private void handleFBLogin() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
LoginManager.getInstance().logOut();
boolean isLoggedIn = accessToken != null && !accessToken.isExpired();
LoginManager.getInstance().logInWithReadPermissions(ActivityLogin.this, Arrays.asList("public_profile", "email"));
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(final LoginResult loginResult) {
runOnUiThread(new Runnable() {
@Override
public void run() {
setFacebookData(loginResult, d);
}
});
}
@Override
public void onCancel() {
Toast.makeText(getApplicationContext(), "Canceled login ", Toast.LENGTH_SHORT); toast.show();
}
@Override
public void onError(FacebookException exception) {
d.dismiss();
if (exception instanceof FacebookAuthorizationException) {
if (AccessToken.getCurrentAccessToken() != null) {
LoginManager.getInstance().logOut();
handleFBLogin();
return;
}
}
Toast.makeText(getApplicationContext(), "ERROR " + exception.toString(), Toast.LENGTH_SHORT); toast.show();
PackageInfo info;
try {
info = getPackageManager().getPackageInfo([your package name], PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md;
md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String something = new String(Base64.encode(md.digest(), 0));
//String something = new String(Base64.encodeBytes(md.digest()));
Log.e("hash key", something);
}
} catch (Exception e1) {
Log.e("name not found", e1.toString());
}
}
});
}
private void setFacebookData(final LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
final String firstName = response.getJSONObject().getString("first_name");
String lastName = response.getJSONObject().getString("last_name");
String id = response.getJSONObject().getString("id");
String email = null;
if (response.getJSONObject().has("email"))
email = response.getJSONObject().getString("email");
//put your code here
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,email,first_name,last_name,gender");
request.setParameters(parameters);
request.executeAsync();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With