skip to Main Content

Hello Every One I am building an android app for my project and I have error in Facebook login and Twitter Login is not working

Here is my code for mainActivity.java

package com.example.creative.fbtest;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

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.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.TwitterSession;
import com.twitter.sdk.android.core.identity.TwitterLoginButton;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;

public class MainActivity extends AppCompatActivity implements android.view.View.OnClickListener,GoogleApiClient.OnConnectionFailedListener {
    //initialization
    private LoginButton loginButtonFb;
    private TextView textViewStatus;
    private CallbackManager FBcallbackManager;
    private LoginManager loginManager;
    private SignInButton signInButtonGoogle;
    private Button signOutButtonGoogle;
    private GoogleApiClient googleApiClient;
    private TextView txtEmail,txtName;
    private static final int request_code = 10;
    private LinearLayout profile_google;
    private ImageView prof_pic;
    private TwitterLoginButton signInButtonTwitter;






    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //initializing Facebook Sdk
       // FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        loginButtonFb = (LoginButton) findViewById(R.id.fb_login_button);
        textViewStatus = (TextView) findViewById(R.id.txt_login_status);

        //initialize
        profile_google = (LinearLayout) findViewById(R.id.profile_google_layout);
        signOutButtonGoogle = (Button) findViewById(R.id.gmail_logout_btn);
        signInButtonGoogle = (SignInButton) findViewById(R.id.google_sign_in_button);
        txtEmail = (TextView) findViewById(R.id.txt_gmail_email);
        txtName=(TextView)findViewById(R.id.txt_gmail_name);
        prof_pic=(ImageView)findViewById(R.id.google_prof_pic);

        //for twitter Login
        signInButtonTwitter=(TwitterLoginButton) findViewById(R.id.twitter_login_button);
        signInButtonTwitter.setCallback(new Callback<TwitterSession>() {
            @Override
            public void success(Result<TwitterSession> result) {

                textViewStatus.setText("Login Successfull Twitter");
            }

            @Override
            public void failure(TwitterException e) {
                textViewStatus.setText("Login Failed  Twitter!");
            }
        });



        //set on click listener
        signInButtonGoogle.setOnClickListener(this);
        signOutButtonGoogle.setOnClickListener(this);
        //display profile after login
        profile_google.setVisibility(View.GONE);

        //initializing sign in options to fetch user
        GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
        // ATTENTION: This "addApi(AppIndex.API)"was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        googleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, signInOptions).build();


        //for accessing user information
        loginButtonFb.setReadPermissions(Arrays.asList("public_profile", "email", "user_birthday", "user_friends"));
        //initialize Callback Manger
        FBcallbackManager= CallbackManager.Factory.create();


        loginButtonFb.registerCallback(FBcallbackManager, new FacebookCallback<LoginResult>() {
            //on success
            @Override
            public void onSuccess(final LoginResult loginResult) {

                //TODO: use the profile class to get information
                //app
                GraphRequest request=GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(JSONObject object, GraphResponse response) {
                                try {
                                    //application code
                                    String name=object.getString("name");
                                    String email=object.getString("email");
                                    Log.e("Name=",""+name);
                                    Toast.makeText(MainActivity.this, "Email"+email, Toast.LENGTH_SHORT).show();
                                }
                                catch (JSONException e)
                                {
                                    Log.e("MYAPP", "unexpected JSON exception", e);
                                }



                            }

                        });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email,gender,birthday");
                request.setParameters(parameters);
                request.executeAsync();
                Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_SHORT).show();

                textViewStatus.setText("Login Successful" + loginResult.getAccessToken().getUserId());
                signInButtonGoogle.setVisibility(View.GONE);
                profile_google.setVisibility(View.GONE);

            }

            @Override
            public void onCancel()

            {
                Toast.makeText(MainActivity.this, "Login Cancel", Toast.LENGTH_SHORT).show();
                loginManager.getInstance().logOut();

                textViewStatus.setText("Login Cancel");
            }

            @Override
            public void onError(FacebookException error) {
                textViewStatus.setText("Some Error Occured"+"/n"+"Error"+error.toString());
                signInButtonGoogle.setVisibility(View.GONE);
                signInButtonTwitter.setVisibility(View.GONE);
                Log.e("Error","Facebook Error",error);

                Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_SHORT).show();

            }
            //to get username



        });



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

//TO DO:Error occurs of facebook and Twitter is not working

            if (requestCode == request_code)
            {
                GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
                handleResult(result);
            }
            else if(requestCode==TwitterAuthConfig.DEFAULT_AUTH_REQUEST_CODE)
        {
            // Pass the activity result to the login button.
            signInButtonTwitter.onActivityResult(requestCode, resultCode, data);
        }
        else
            {
                FBcallbackManager.onActivityResult(requestCode,requestCode,data);

            }
        }





//which button is clicked by user
    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.google_sign_in_button:
                signIn();
                break;
            case  R.id.gmail_logout_btn:
                signOut();;
                break;
        }


    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
    private void signIn()
    {
        try {
            //creating intent variable
            Intent intentGoogleSignIn = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
            startActivityForResult(intentGoogleSignIn, request_code);
        }
        catch (Exception ex)
        {
            Toast.makeText(getApplicationContext(),ex.getMessage(),Toast.LENGTH_SHORT).show();
        }

    }

    private void signOut()
    {
Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(new ResultCallback<Status>() {
    @Override
    public void onResult(@NonNull Status status) {
        updateUI(false);
    }
});
    }
    private void handleResult(GoogleSignInResult result)
    {
        //on login success
        if(result.isSuccess())
        {
            //fetching the user information
            GoogleSignInAccount account=result.getSignInAccount();
            String name=account.getDisplayName();
            String email=account.getEmail();
            //String image_url=account.getPhotoUrl().toString();
            //setting the user information
            txtName.setText(name);
            txtEmail.setText(email);
            //Glide.with(this).load(image_url).into(prof_pic);
            updateUI(true);

        }
        else
        {
            updateUI(false);
        }

    }
    private void updateUI(Boolean isLogin)
    {
        if(isLogin)
        {

            profile_google.setVisibility(View.VISIBLE);
            signInButtonGoogle.setVisibility(View.GONE);

        }
        else
        {
            profile_google.setVisibility(View.GONE);
            signInButtonGoogle.setVisibility(View.VISIBLE);


        }

    }

}

Google Login is perfectly working there are 2 errors

  1. I got error “Unhandled Exception LoginManager.onResultActivity” and code is directly jump to on error block after the login part and authorize part in facebook login.

2.I have written code for twitter but none of the click event is fired although I have written in the above code.

I guess that these two errors is in the below code but not sure

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

//TO DO:Error occurs of facebook and Twitter is not working

            if (requestCode == request_code)
            {
                GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
                handleResult(result);
            }
            else if(requestCode==TwitterAuthConfig.DEFAULT_AUTH_REQUEST_CODE)
        {
            // Pass the activity result to the login button.
            signInButtonTwitter.onActivityResult(requestCode, resultCode, data);
        }
        else
            {
                FBcallbackManager.onActivityResult(requestCode,requestCode,data);

            }
        }

I got stucked in my project please someone help me Thank You

4

Answers


  1. Chosen as BEST ANSWER

    I have Solved the problem There are some changes I made

    //Initialized Twitter Sdk fabric

    TwitterAuthConfig autoConfig=new TwitterAuthConfig(TwKey,TwSecreteKey);
            Fabric.with(this,new TwitterCore(autoConfig));
    

    //Here was mistake I made FBcallbackManager.onActivityResult(requestCode, requestCode, data);

    //correct is

    FBcallbackManager.onActivityResult(requestCode, resultCode, data);
    

  2. Try this way..

        @Override
        protected void onActivityResult(int requestCode,int resultCode,Intent data)
            {
                        super.onActivityResult(requestCode,resultCode,data);
                        FBcallbackManager.onActivityResult(requestCode,requestCode,data);
                        signInButtonTwitter.onActivityResult(requestCode, resultCode, data);
    
    
                            if (requestCode == request_code)
                            {
                                GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
                                handleResult(result);
                            }
            }
    
    Login or Signup to reply.
  3. I was able to achieve with this implementation. Please try this:

     @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // Result returned from launching the Intent from
        //   GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            //Google44
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                GoogleSignInAccount acct = result.getSignInAccount();
                // Get account information
                String mFullName = acct.getDisplayName();
                String mEmail = acct.getEmail();
                String googlePlusToken = acct.getIdToken().trim();
                googlePlusDetails = mFullName + ", " + mEmail + ", id: " + acct.getId() + ", photoUrl: " + acct.getPhotoUrl();
                Log.d(TAG, mFullName + "," + mEmail + "," + acct.toString());
                Log.d(TAG, googlePlusDetails);
                /**
                 * google Token
                 */
    
            } else {
                Log.e(TAG, "Result: " + result.getStatus());
                Log.e(TAG, "Result: " + result.getStatus().getStatusMessage());
                Log.e(TAG, "Google plus sign-in failed");
                showToast("Google plus sign-in failed");
            }
        } else if (requestCode == TwitterAuthConfig.DEFAULT_AUTH_REQUEST_CODE) {
            // TWITTER
            loginButton.onActivityResult(requestCode, resultCode, data);
    
        } else {
            //FACEBOOK
            callbackManager.onActivityResult(requestCode, resultCode, data);
        }
    
    
    }
    
    Login or Signup to reply.
  4. import android.content.Intent;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.RelativeLayout;
    import android.widget.TextView;
    
    import com.facebook.CallbackManager;
    import com.facebook.FacebookCallback;
    import com.facebook.FacebookException;
    import com.facebook.FacebookSdk;
    import com.facebook.GraphRequest;
    import com.facebook.GraphResponse;
    import com.facebook.login.LoginResult;
    import com.facebook.login.widget.LoginButton;
    import com.facebook.login.widget.ProfilePictureView;
    
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import java.util.Arrays;
    
    public class MainActivity extends AppCompatActivity {
    
        CallbackManager callbackManager;
        LoginButton loginButton;
        ProfilePictureView profilePictureView;
        RelativeLayout relativeLayout;
        TextView tv_email,tv_name,tv_gender,tv_dob;
    
        @Override
        protected void onCreate( Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            FacebookSdk.sdkInitialize(getApplicationContext());
            setContentView(R.layout.activity_main);
    
             tv_dob=(TextView)findViewById(R.id.tv_dob);
            tv_email=(TextView)findViewById(R.id.tv_email);//1
            tv_name=(TextView)findViewById(R.id.tv_name);//2
            tv_gender=(TextView)findViewById(R.id.tv_gender);//3
            loginButton=(LoginButton)findViewById(R.id.loginButton);//4
            relativeLayout=(RelativeLayout)findViewById(R.id.relative_layout);//5
            profilePictureView=(ProfilePictureView)findViewById(R.id.ppv_dp);//6
    
            loginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday"));
    
            callbackManager = CallbackManager.Factory.create();
    
            loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {
                    GraphRequest graphRequest=GraphRequest.newMeRequest(
                            loginResult.getAccessToken(),
                            new GraphRequest.GraphJSONObjectCallback(){
    
                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {
                            Log.e("RESPONSE",response.toString());
                            setProfileToView(object);
                        }
                    });
    
                    Bundle bundle=new Bundle();
                    bundle.putString("fields", "id,name,email,gender, birthday");
                    graphRequest.setParameters(bundle);
                    graphRequest.executeAsync();
    
                    Log.e("LOGIN_RESULT",loginResult.toString());
                }
    
                @Override
                public void onCancel() {
    
                }
    
                @Override
                public void onError(FacebookException error) {
                    Log.e("ERROR_LOGIN_TO_Fb",error.toString());
                }
            });
    
    
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode,resultCode,data);
            callbackManager.onActivityResult(requestCode, resultCode, data);
        }
        private void setProfileToView(JSONObject jsonObject) {
            try {
                tv_email.setText(jsonObject.getString("email"));
                tv_gender.setText(jsonObject.getString("gender"));
                tv_name.setText(jsonObject.getString("name"));
                tv_dob.setText(jsonObject.getString("birthday"));
                Log.e("dob",tv_dob.toString());
    
                profilePictureView.setPresetSize(ProfilePictureView.NORMAL);
                profilePictureView.setProfileId(jsonObject.getString("id"));
                relativeLayout.setVisibility(View.VISIBLE);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search