1

Trying to integrate Facebook Login in android app. The login and logout is working fine but sometimes even after login in, profile is still null. As soon as I get the details from Facebook I logout. I referred to some other questions on Stackoverflow, and applied it in the code but somewhere still something is going wrong and not able to figure it out.

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.login_activity);
    callbackManager = CallbackManager.Factory.create();
    loginButton = (LoginButton) findViewById(R.id.btnFacebookSignin);
    loginButton.setReadPermissions("public_profile, email");
    loginButton.registerCallback(callbackManager, facebookCallback);
}

FacebookCallback<LoginResult> facebookCallback = new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {

            if(Profile.getCurrentProfile() == null) {
                mProfileTracker = new ProfileTracker() {
                    @Override
                    protected void onCurrentProfileChanged(Profile profile, Profile profile2) {
                        Log.v("facebook - profile", profile2.getFirstName());
                        mProfileTracker.stopTracking();
                    }
                };
                mProfileTracker.startTracking();
            }
            else {
                Profile profile = Profile.getCurrentProfile();
                Log.v("facebook - profile", profile.getFirstName());
            }
            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {

                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {

                            if (BuildConfig.DEBUG) {
                                FacebookSdk.setIsDebugEnabled(true);
                                FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

                                Profile profile = Profile.getCurrentProfile();
                                if (profile != null) {

                                    String name = profile.getName();
                                    Uri pictureUri = profile.getProfilePictureUri(200, 200);
                                    String email = object.optString("email");
                                    String uid = object.optString("id");
                                    try {
                                        sendLogin(uid, name, email, pictureUri.toString(), "fb");
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    facebookLogout();
                                } else {
                                    facebookLogout();
                                    Toast.makeText(getApplication(), "Something went wrong, please try again later", Toast.LENGTH_LONG).show();
                                }
                            }
                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "email");
            request.setParameters(parameters);
            request.executeAsync();
        }

        @Override
        public void onCancel() {
        }

        @Override
        public void onError(FacebookException e) {
            Toast.makeText(getApplication(), "Something went wrong, please try again later", Toast.LENGTH_LONG).show();
        }
    };

    public void facebookLogout() {
        LoginManager.getInstance().logOut();
    }
Jay Visariya
  • 83
  • 2
  • 18

2 Answers2

1

Try this Code I hope Its Work..

   facebookimage(object.getString("id"));

This is Method:

 private void facebookimage(String id) {
        new getFacebookImage(id).execute();
    }

This is AsyncTask class to get Profile Image on Facebook ;

private class getFacebookImage extends AsyncTask {

        String userID;
        Bitmap camera;

        public getFacebookImage(String id) {
            userID=id;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Object doInBackground(Object[] params) {


            URL imageURL = null;
            Bitmap bitmap=null;
            try {
                imageURL = new URL("https://graph.facebook.com/" + userID + "/picture?type=large");
                bitmap = BitmapFactory.decodeStream(imageURL.openConnection().getInputStream());
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.e("String Image",""+bitmap);
            camera=bitmap;
            return bitmap;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);

            if(camera != null){
                Log.e("Image Load","UPload image");
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                camera.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                byte imageInByte[] = stream.toByteArray();
                String encodedImage = Base64.encodeToString(imageInByte, Base64.DEFAULT);
                DataBase.setUserImage(LoginActivity.this,encodedImage);

            }

        }
    }
Abhinav singh
  • 1,448
  • 1
  • 14
  • 31
0

Initially I was getting only id and email in JSONObject object of onCompleted. Even though I set permissions like "public_profile" and "email" which is sufficient enough to get the id, name, email and profile picture from facebook. But somewhere I went wrong and didn't understand and added Profile and did getProfile() so I can get the name and profile picture. Then other problem arised was even after login perfectly, I was getting null profile sometimes(may be once in 5 times). For that had to put Profile Tracker and this was because Profile works Asynchronously(was too confusing for me as you have to put trackers and start & stop tracking).

Then I realized where I went wrong. In the bundle where we need to mention what all we want in the json object as reply, I had only mentioned "id". So now in the below code I added "name" and "email" as well. So in the JSONObject object response I get the name and email as well.

And for profile picture I saw How can I display the users profile pic using the facebook graph api? and implemented this using Uri builder Use URI builder in Android or create URL with variables . So with this I removed the use of Profile completely and still getting all the data I wanted.

This answer is the mixture of both the answers mentioned by Destro - Android Facebook Login- Profile is null & How to get email id From Android Facebook SDK 4.6.0?

FacebookCallback<LoginResult> facebookCallback = new FacebookCallback<LoginResult>() {

        @Override
        public void onSuccess(final LoginResult loginResult) {


            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {

                            if (BuildConfig.DEBUG) {
                                FacebookSdk.setIsDebugEnabled(true);
                                FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);


                                String uid = object.optString("id");
                                String email = object.optString("email");
                                String name = object.optString("name");

                                Uri.Builder builder = new Uri.Builder();
                                builder.scheme("https")
                                        .authority("graph.facebook.com")
                                        .appendPath(uid)
                                        .appendPath("picture")
                                        .appendQueryParameter("width", "1000")
                                        .appendQueryParameter("height", "1000");

                                Uri pictureUri = builder.build();

                                try {
                                    sendLogin(uid, name, email, pictureUri.toString(), "fb");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                facebookLogout();

                            }
                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id, name, email");
                    request.setParameters(parameters);
            request.executeAsync();
        }

        @Override
        public void onCancel() {
        }

        @Override
        public void onError(FacebookException e) {
            Toast.makeText(getApplication(), "Something went wrong, please try again later", Toast.LENGTH_LONG).show();
        }
    };

    public void facebookLogout() {
        LoginManager.getInstance().logOut();
    }
Community
  • 1
  • 1
Jay Visariya
  • 83
  • 2
  • 18
  • this code is working for me but in signed apk its not working. I have updated release keyhash on facebook developer. please let know what I need to change. Thanks – vijay chhalotre Aug 30 '17 at 11:05