Hammad Nasir Hammad Nasir - 23 days ago 8
Android Question

How to know if the user has signed up using email or facebook?

I have integrated 2 types of sign up options in my app. One with email and other with Facebook. I have integrated them successfully, but I am unable to know that whether the user signed up using Facebook or email so that I can proceed accordingly.

Here's my code:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);

userName = (EditText) findViewById(R.id.userName);
userEmail = (EditText) findViewById(R.id.userEmail);
userPassword = (EditText) findViewById(R.id.userPassword);
userPasswordAgain = (EditText) findViewById(R.id.userPasswordAgain);
signUpBtn = (AppCompatButton) findViewById(R.id.btnSignup);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
progressDialog = new ProgressDialog(SignUpActivity.this);

FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);

callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("email", "user_friends", "public_profile");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d("facebookLogin", "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
}

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

@Override
public void onError(FacebookException error) {
Snackbar snackbar = Snackbar
.make(coordinatorLayout, error.getMessage(), Snackbar.LENGTH_SHORT);
snackbar.show();
}
});

mAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference();

loginLabel = (TextView) findViewById(R.id.loginLabel);
loginLabel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent loginActivity = new Intent(SignUpActivity.this, LoginActivity.class);
startActivity(loginActivity);
}
});

mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d("signedIn", "onAuthStateChanged:signed_in:" + user.getUid());
mDatabase.child("users").child(user.getUid()).child("name").setValue(userName.getText().toString());
mDatabase.child("users").child(user.getUid()).child("uniqueUserName").setValue(uniqueUserName.getText().toString());
mDatabase.child("users").child(user.getUid()).child("followers").setValue("00");
mDatabase.child("users").child(user.getUid()).child("following").setValue("00");
mDatabase.child("unique-usernames").child(ts).setValue(uniqueUserName.getText().toString());
Intent mainIntent = new Intent(SignUpActivity.this, SplashActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
progressDialog.dismiss();
} else {
// User is signed out
Log.d("signedOut", "onAuthStateChanged:signed_out");
}
// ...
}
};

signUpBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isNetworkAvailable()) {
signUpUser();
} else {
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "No internet connection", Snackbar.LENGTH_SHORT);
snackbar.show();
}
}
});


}

public void signUpUser() {
if (userName.getText().toString().isEmpty()) {
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Name cannot be empty", Snackbar.LENGTH_SHORT);
snackbar.show();
} else if (userEmail.getText().toString().isEmpty()) {
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Email cannot be empty", Snackbar.LENGTH_SHORT);
snackbar.show();
} else if (userPassword.getText().toString().isEmpty()) {
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Password cannot be empty", Snackbar.LENGTH_SHORT);
snackbar.show();
} else if (userPasswordAgain.getText().toString().isEmpty()) {
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Please re-type password", Snackbar.LENGTH_SHORT);
snackbar.show();
} else if (!userPassword.getText().toString().equals(userPasswordAgain.getText().toString())) {
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Password do not match", Snackbar.LENGTH_SHORT);
snackbar.show();
} else {
if (dialog == null) {

final AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);

LayoutInflater inflater = this.getLayoutInflater();
View alertDialogView = inflater.inflate(R.layout.choose_unique_name_dialog, null);
uniqueUserName = (EditText) alertDialogView.findViewById(R.id.uniqueUserName);
usernameChoosen = (TextView) alertDialogView.findViewById(R.id.usernameChoosen);
usernameWarning = (TextView) alertDialogView.findViewById(R.id.usernameWarning);

usernameChoosen.setVisibility(View.INVISIBLE);
usernameWarning.setVisibility(View.INVISIBLE);

builder.setTitle("Choose a unique username");
builder.setView(alertDialogView);
builder.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
signingUpMethod();
}
});
dialog = builder.create();
}
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
wantToCloseDialog = false;
//Do stuff, possibly set wantToCloseDialog to true then...
if (uniqueUserName.getText().toString().isEmpty()) {
// Snackbar snackbar = Snackbar
// .make(coordinatorLayout, "Please choose a unique username", Snackbar.LENGTH_SHORT);
// snackbar.show();
Toast.makeText(getBaseContext(), "Please choose a unique username", Toast.LENGTH_LONG).show();
wantToCloseDialog = false;
} else {

mDatabase.child("unique-usernames").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
if (dataSnapshot.getValue().toString().contains(uniqueUserName.getText().toString())) {
Toast.makeText(getBaseContext(), uniqueUserName.getText().toString() + " is already taken", Toast.LENGTH_LONG).show();
usernameChoosen.setText(uniqueUserName.getText().toString());
wantToCloseDialog = false;
} else {
signingUpMethod();
wantToCloseDialog = true;
}
} else {
signingUpMethod();
wantToCloseDialog = true;
}
}

@Override
public void onCancelled(DatabaseError databaseError) {
Snackbar snackbar = Snackbar
.make(coordinatorLayout, databaseError.getMessage(), Snackbar.LENGTH_LONG);
snackbar.show();
wantToCloseDialog = false;
}
});
}
if(wantToCloseDialog)
dialog.dismiss();
//else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
}
});
}
}

public void signingUpMethod() {
progressDialog.setMessage("Signing up...");
progressDialog.setCancelable(false);
progressDialog.show();
mAuth.createUserWithEmailAndPassword(userEmail.getText().toString(), userPassword.getText().toString())
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d("signUpSuccessful", "createUserWithEmail: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.d("exception", "onComplete: Failed=" + task.getException().getMessage());
new AlertDialog.Builder(SignUpActivity.this)
.setMessage(task.getException().getMessage())
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
progressDialog.dismiss();
}

// ...
}
});
}

private void handleFacebookAccessToken(AccessToken token) {
Log.d("token", "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("facebookSignInSuccess", "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("facebookSignInFailed", "signInWithCredential", task.getException());
Toast.makeText(SignUpActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}

// ...
}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}


In the docs here, it says in point 4 that


If the call to signInWithCredential succeeds, the AuthStateListener runs the onAuthStateChanged callback. In the callback, you can use the getCurrentUser method to get the user's account data.


But the
AuthStateListener
has already the code for email login.

So, I want to know that with what code I can know that if the user has signed up using facebook so that I can put the related code in this block and if he has signed up using email, I can put the related code in this block.

Please let me know.

Answer

You can store the boolean isFacebookUser to to true when facebook login is clicked and isFacebookUser to false when simple login button is click.

Check the isFacebookUser boolean where-ever you need. That's all!

Or

You can check with the following method from Facebook SDK.

public boolean isFacebookLoggedIn() {
    return AccessToken.getCurrentAccessToken() != null;
}