Start an activity in firebase facebook authentication code - android

Why i can't startActivity in the facebook authentification code ?
1.The code is running well except that after the login i want to start an activity ,mean it should be somewhere to put the startActivity methode
public class LoginActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private static final String TAG = "Login";
private CallbackManager mCallbackManager;
Intent intent=new Intent(this,MainActivity.class);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_login);
AppEventsLogger.activateApp(this);
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");
}
// ...
}
};
// Initialize Facebook Login button
mCallbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
//startActivity(intent);
}
#Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
// ...
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError", error);
// ...
}
});
// ...
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
// ...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Pass the activity result back to the Facebook SDK
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}private void handleFacebookAccessToken(AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
// [START_EXCLUDE silent]
//showProgressDialog
// [END_EXCLUDE]
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();
}
// [START_EXCLUDE]
//hideProgressDialog();
// [END_EXCLUDE]
}
});
}
// [END auth_with_facebook]
}

You can do this in your AuthStateListener where currently you have:
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());
// you can also add anything else that should happen when user
// has successfully signed in
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
As the comment states, when user != null the user is signed in, so that's where you can start your Activity or whatever you want to do.
When the user is successfully signed into Firebase Auth via Facebook (or any other logins you add) the onAuthStateChanged method will be called.

Related

Android Firebase Facebook Authentication Logout function

I am using the facebook auth medthod with firebase and I can't figure out how to properly Log out a user. After I press the 'Continue with Facebook' button and give it access to my profile the button changes in 'Log out' and shows a dialog when I click it. The problem is that it doesn't actually log me out and the state is still signed in.
I found here how to log out the user from Firebase and Facebook in my app but I can't figure out where to put those 2 lines. I am looking for a Logout function or something like that.
I found here (different here) what might be my solution but it's pretty messy and can't understand. Can you please help me?
#Override
protected void onCreate(Bundle savedInstanceState) {
mAuth = FirebaseAuth.getInstance();
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
setContentView(R.layout.activity_login);
mCallbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.e(TAG, "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.e(TAG, "facebook:onCancel");
// ...
}
#Override
public void onError(FacebookException error) {
Log.e(TAG, "facebook:onError", error);
// ...
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
final FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.e(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
DatabaseReference myRef = database.getReference("Users");
myRef.addValueEventListener(new ValueEventListener() {
boolean userExists = false;
User userFirebase;
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot mydata : dataSnapshot.getChildren()){
userFirebase = mydata.getValue(User.class);
if(userFirebase.getEmail().equals(user.getEmail())){
Log.e(TAG, "User found in the database");
userExists = true;
Intent intent = new Intent(getBaseContext(), ActivityMain.class);
startActivity(intent);
break;
}
}
if (!userExists){
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("Users").push().setValue(new User(user.getDisplayName(),user.getEmail(),0,0));
Intent intent = new Intent(getBaseContext(), ActivityMain.class);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}); // checks if the user is in database and writes him if not
} else {
// User is signed out
Log.e(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);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Pass the activity result back to the Facebook SDK
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
private void handleFacebookAccessToken(AccessToken token) {
Log.e(TAG, "handleFacebookAccessToken:" + token);
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.e(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.e(TAG, "signInWithCredential", task.getException());
Toast.makeText(getBaseContext(), "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
You need to implement your own button and add and OnClickListener with the 2 methods mentioned :
Button logoutButton = (Button) findViewById(R.id.logout_button);
logoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
LoginManager.getInstance().logOut();
}
});
You can't use the facebook logout button , because it only logs you out of facebook and you need the firebase logout aswell.

Facebook authentication in firebase not working

What I'm trying to do is login with Facebook using Firebase and then get name, email, profile picture and uid and then store it to Firebase Database.
Everything is working fine until clicking on login button and then the Facebook account window pop up. After that, when I select an account by clicking "Continue With Rishabh", nothing happens.
No authentication, no error, nothing. Same Facebook account selection window stays on screen and nothing happens.
Any help will be appreciated.
Here is my SignInActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
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");
}
// ...
}
};
mSignInToolbar = (Toolbar) findViewById(R.id.signInToolbar);
setSupportActionBar(mSignInToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mRef = FirebaseDatabase.getInstance().getReference().child("Users");
mRef.keepSynced(true);
mEmailField = (EditText) findViewById(R.id.emailField);
mPasswordField = (EditText) findViewById(R.id.passowrdField);
mSigninBtn = (Button) findViewById(R.id.signinBtn);
mProgress = new ProgressDialog(this);
// Initialize Facebook Login button
FacebookSdk.sdkInitialize(getApplicationContext());
mCallbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
// ...
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError", error);
// ...
}
});
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Pass the activity result back to the Facebook SDK
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
private void handleFacebookAccessToken(AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
mProgress.setMessage("Logging in...");
mProgress.show();
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(SignInActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
mProgress.dismiss();
}else{
String uid=task.getResult().getUser().getUid();
String name=task.getResult().getUser().getDisplayName();
String email=task.getResult().getUser().getEmail();
String image=task.getResult().getUser().getPhotoUrl().toString();
DatabaseReference childRef = mRef.child(uid);
childRef.child("name").setValue(name);
childRef.child("email").setValue(email);
childRef.child("image").setValue(image);
mProgress.dismiss();
Intent mainIntent = new Intent(getApplicationContext(), MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainIntent);
}
}
});
}
See what all you need to do is to change some permission in facebook developer page. See the below picture make sure you too make required permission "Yes" as I did :
FacebookSdk.sdkInitialize(getApplicationContext());
Put this in the Application.
I've solved my problem by running the application in a real device (not in the emulator).

Facebook login with Firebase Authentication

I'm using Firebase Auth in my Android application, but I have a problem.
I can link my app to my Facebook from my phone and once they are linked, my Firebase user still null. I don't know why.
Does someone have an idea of what is happening? Below is my code.
I'm following the steps on Firebase GitHub repo. I am using Firebase 9.0.1.
mAuth = FirebaseAuth.getInstance();
mCallbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.facebook_connexion_button);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
startActivity(new Intent(ConnectActivity.this,Events.class));
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
// [START_EXCLUDE]
//updateUI(null);
// [END_EXCLUDE]
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError", error);
// [START_EXCLUDE]
//updateUI(null);
// [END_EXCLUDE]
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
dataIntoPref(user.getDisplayName(),String.valueOf(user.getPhotoUrl()));
Toast.makeText(ConnectActivity.this,user.getDisplayName(),Toast.LENGTH_SHORT).show();
startActivity(new Intent(ConnectActivity.this,Events.class));
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Toast.makeText(ConnectActivity.this,"User is Null",Toast.LENGTH_SHORT).show();
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);
}
}
the handleFacebookAccessToken is wrotten like this:
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(ConnectActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// [START_EXCLUDE]
// hideProgressDialog();
// [END_EXCLUDE]
}
});

Firebase Facebook authentication showing weird activity

We are implementing Firebase Facebook authentication for one of our projects. We have followed the steps mentioned in the documentation as well.
Here is the oAuth URL:
https://<APP_NAME>.firebaseapp.com/__/auth/handler
I've added the rest of the credentials as well (i.e the APP_ID & APP_SECRET), moreover the app is in development stage and I've added the key hash as well to the Facebook portal and Firebase portal.
The Login initial flow works well, but when the user confirm the permission to grant access, the callback register doesn't respond at all, neither with negative nor positive acknowledgement.
Here's our piece of code:
private static final String TAG = "FacebookLogin";
private CallbackManager mCallbackManager;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
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");
}
// ...
}
};
// Initialize Facebook Login button
mCallbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
// ...
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError"+ error);
// ...
}
});
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void handleFacebookAccessToken(AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
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(FacebookLoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
Please let us know if we missed anything. I'm assuming there's something wrong about the callback URL, thus a bit more information on the same would be helpful as Firebase documentation doesn't clearly state about how to build up that URL. Thanks in advance.
Did you add
mCallbackManager.onActivityResult(requestCode, resultCode, data);
in your onActivityResult block?
Edit
Referring to the sample from Firebase https://github.com/firebase/quickstart-android/blob/master/auth/app/src/minSdkJellybean/java/com/google/firebase/quickstart/auth/FacebookLoginActivity.java,
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
If this is not added, there would be no callback.

Facebook Login via Firebase - Access_Token_Denied Error

Facebook logs in correctly. In the Firebase console, I can see the user has logged. However, I cannot access any of the user's info.
I am getting below error log in LogCat:
signInWithFacebook:{AccessToken token:ACCESS_TOKEN_REMOVED
permissions:[public_profile, contact_email, user_friends, email]}
Afterwards, I also receive a FirebaseError: Permission denied in the LogCat and as a toast inside the app.
Following this tutorial, I have made a project that integrates Facebook and Firebase. I've tried copy and pasting the source code, and replacing the necessary lines (such as Facebook ID and Firebase URL) but it isn't working for me.
here is the specific void
private void signInWithFacebook(AccessToken token) {
Log.d(TAG, "signInWithFacebook:" + token.getToken());
showProgressDialog();
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{
String uid=task.getResult().getUser().getUid();
String name=task.getResult().getUser().getDisplayName();
String email=task.getResult().getUser().getEmail();
String image=task.getResult().getUser().getPhotoUrl().toString();
//Create a new User and Save it in Firebase database
User user = new User(uid,name,null,email,name);
mRef.child(uid).setValue(user);
Log.d(TAG, uid);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("user_id",uid);
intent.putExtra("profile_picture",image);
startActivity(intent);
finish();
}
hideProgressDialog();
}
});
}
here is the full code
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "AndroidBash";
public User user;
private EditText email;
private EditText password;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private ProgressDialog mProgressDialog;
private DatabaseReference mDatabase;
//Add YOUR Firebase Reference URL instead of the following URL
private Firebase mRef=new Firebase("https://firebase.firebaseio.com");
//FaceBook callbackManager
private CallbackManager callbackManager;
//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDatabase = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
if (mUser != null) {
// User is signed in
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
String uid = mAuth.getCurrentUser().getUid();
String image=mAuth.getCurrentUser().getPhotoUrl().toString();
intent.putExtra("user_id", uid);
if(image!=null || image!=""){
intent.putExtra("profile_picture",image);
}
startActivity(intent);
finish();
Log.d(TAG, "onAuthStateChanged:signed_in:" + mUser.getUid());
}
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser mUser = firebaseAuth.getCurrentUser();
if (mUser != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + mUser.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
}
};
//FaceBook
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
signInWithFacebook(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError", error);
}
});
//
}
#Override
protected void onStart() {
super.onStart();
email = (EditText) findViewById(R.id.edit_text_email_id);
password = (EditText) findViewById(R.id.edit_text_password);
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
//FaceBook
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
//
protected void setUpUser() {
user = new User();
user.setEmail(email.getText().toString());
user.setPassword(password.getText().toString());
}
public void onSignUpClicked(View view) {
Intent intent = new Intent(this, SignUpActivity.class);
startActivity(intent);
}
public void onLoginClicked(View view) {
setUpUser();
signIn(email.getText().toString(), password.getText().toString());
}
private void signIn(String email, String password) {
Log.d(TAG, "signIn:" + email);
if (!validateForm()) {
return;
}
showProgressDialog();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithEmail: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, "signInWithEmail", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
String uid = mAuth.getCurrentUser().getUid();
intent.putExtra("user_id", uid);
startActivity(intent);
finish();
}
hideProgressDialog();
}
});
//
}
private boolean validateForm() {
boolean valid = true;
String userEmail = email.getText().toString();
if (TextUtils.isEmpty(userEmail)) {
email.setError("Required.");
valid = false;
} else {
email.setError(null);
}
String userPassword = password.getText().toString();
if (TextUtils.isEmpty(userPassword)) {
password.setError("Required.");
valid = false;
} else {
password.setError(null);
}
return valid;
}
private void signInWithFacebook(AccessToken token) {
Log.d(TAG, "signInWithFacebook:" + token.getToken());
showProgressDialog();
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{
String uid=task.getResult().getUser().getUid();
String name=task.getResult().getUser().getDisplayName();
String email=task.getResult().getUser().getEmail();
String image=task.getResult().getUser().getPhotoUrl().toString();
//Create a new User and Save it in Firebase database
User user = new User(uid,name,null,email,name);
mRef.child(uid).setValue(user);
Log.d(TAG, uid);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("user_id",uid);
intent.putExtra("profile_picture",image);
startActivity(intent);
finish();
}
hideProgressDialog();
}
});
}
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
}

Categories

Resources