0

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.

adjuremods
  • 2,938
  • 2
  • 12
  • 17
Hammad Nasir
  • 2,889
  • 7
  • 52
  • 133
  • You can loop over the provider data to find out what provider(s) the user signed in with. See http://stackoverflow.com/questions/38619628/how-to-determine-if-a-firebase-user-is-signed-in-using-facebook-authentication/38619970#38619970 – Frank van Puffelen Nov 17 '16 at 12:46
  • @FrankvanPuffelen yes, this is what I was looking for. I'll use this code and will respond with what happened. – Hammad Nasir Nov 17 '16 at 13:24

2 Answers2

1

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;
}
android_griezmann
  • 3,757
  • 4
  • 16
  • 43
  • isn't there any way to check the provider with which we are signing up? – Hammad Nasir Nov 17 '16 at 07:04
  • To add to that answer, you can even use the `Profile` class of facebook sdk to check whether user loggedin using facebook. `if(Profile profile != null) then return false;` – eshb Nov 17 '16 at 11:24
  • thanks for the answer... can you help with this too: http://stackoverflow.com/questions/40661629/getting-e-androidruntime-error-reporting-crash-android-os-transactiontoolargee – Hammad Nasir Nov 17 '16 at 17:49
0

simply check when he signup u get facebook id or not, if you get one its a facebook signup else you can assume it to be email signup as you have only 2 signup options here

Ak9637
  • 990
  • 6
  • 12
  • isn't there any way to check the provider with which we are signing up? – Hammad Nasir Nov 17 '16 at 07:04
  • i m not sure how it works in the firebase architecture that you are using here,but simple approach is to set fields on signup and then check which field was set at response,surely if implemented correctly only one field would be set.for example i use signIn=1/2/3 ,acc to signup type and then use this int value to know what type of signup was done at response time.However i would suggest you to go through firebase docs before trying this approach – Ak9637 Nov 17 '16 at 07:08