Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Facebook SDK

  • 31-08-2015 7:44pm
    #1
    Registered Users, Registered Users 2 Posts: 7,893 ✭✭✭


    Hi,

    I'm trying to do a basic login to Facebook, in order to get simple data (email address).

    I'm using Android Studio and the latest version of the Facebook SDK (4.5).
    I followed the steps on the Facebook Dev site, but I'm having issues.

    Has anyone successfully used the 4.x Facebook API on Android?

    There's guides there on the site but they're all samples of the 3.x API, so then when I find some half samples on other sites.
    Case in point:
    https://developers.facebook.com/docs/facebook-login/android

    This uses stuff like the UiLifecycleHelper and Session but they're from the 3.x API.

    Basically the Facebook site seems to extoll the virtues of using the latest 4.x version but all the samples are from 3.x.

    It's doing me nut in at this stage. Even the samples I can find from Google are 3.x.

    Does anyone have a sample of just a Facebook button that pops up the login, lets the user login, and then gets the users email and returns to the app?

    Thanks.


Comments

  • Registered Users, Registered Users 2 Posts: 33 driveshark


    Can you post code you've tried? The Facebook API docs are pretty terrible, I know.


  • Registered Users, Registered Users 2 Posts: 7,893 ✭✭✭The_B_Man


    I've 3 lots of code from 3 different places that I'm trying out.

    The problem with these is that the callbacks dont seem to get called. Possibly I'm not wiring the button in XML up to the callback code. I'm not sure.

    FIRST
    private void testFacebookLogin() {
    	//Customise Facebook login button
    	LoginButton loginButton = (LoginButton) rootView.findViewById(R.id.login_button);
    	loginButton.setFragment(this);
    	//loginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday"));
    	loginButton.setReadPermissions("email");
    	loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
    		@Override
    		public void onSuccess(LoginResult loginResult) {
    			Log.d(TAG, "onSuccess");
    		}
    
    		@Override
    		public void onCancel() {
    			Log.d(TAG, "onCancel");
    		}
    
    		@Override
    		public void onError(FacebookException e) {
    			Log.e(TAG, "onError");
    		}
    	});
    
    	LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
    		@Override
    		public void onSuccess(LoginResult loginResult) {
    			Log.d(TAG, "onSuccess");
    			ProgressDialog progressDialog = new ProgressDialog(getActivity());
    			progressDialog.setMessage("Processing data...");
    			progressDialog.show();
    			String accessToken = loginResult.getAccessToken().getToken();
    			Log.d(TAG, "Access token: " + accessToken);
    
    			GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
    				@Override
    				public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
    					Log.d("LoginActivity", graphResponse.toString());
    					// Get facebook data from login
    					Bundle bFacebookData = getFacebookData(jsonObject);
    					//TODO: Output Facebook data...
    					if(null != bFacebookData) {
    						String email = bFacebookData.getString("email");
    						Log.d(TAG, "users email: " + email);
    					} else {
    						Log.e(TAG, "Facebook data is null");
    					}
    				}
    			});
    
    			Bundle parameters = new Bundle();
    			//parameters.putString("fields","id, first_name, last_name, email,gender, birthday, location");
    			parameters.putString("fields","email");
    			request.setParameters(parameters);
    			request.executeAsync();
    		}
    
    		@Override
    		public void onCancel() {
    			Log.d(TAG, "Facebook login cancel");
    		}
    
    		@Override
    		public void onError(FacebookException e) {
    			Log.e(TAG, "Error logging into Facebook", e);
    		}
    	});
    }
    
        private Bundle getFacebookData(JSONObject object) {
            try {
                Bundle bundle = new Bundle();
                String id = object.getString("id");
    
                try {
                    URL profile_pic = new URL("https://graph.facebook.com/" + id + "/picture?width=200&height=150");
                    Log.i("profile_pic", profile_pic + "");
                    bundle.putString("profile_pic", profile_pic.toString());
    
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                    return null;
                }
    
                bundle.putString("idFacebook", id);
                if (object.has("first_name"))
                    bundle.putString("first_name", object.getString("first_name"));
                if (object.has("last_name"))
                    bundle.putString("last_name", object.getString("last_name"));
                if (object.has("email"))
                    bundle.putString("email", object.getString("email"));
                if (object.has("gender"))
                    bundle.putString("gender", object.getString("gender"));
                if (object.has("birthday"))
                    bundle.putString("birthday", object.getString("birthday"));
                if (object.has("location"))
                    bundle.putString("location", object.getJSONObject("location").getString("name"));
    
                return bundle;
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }
    


    SECOND
        private void testFacebookLoginButton() {
            LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email"));
    
            LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {
                    requestUserProfile(loginResult);
                }
    
                @Override
                public void onCancel() {
                    Toast.makeText(getActivity(), "Login Cancelled", Toast.LENGTH_SHORT).show();
                }
    
                @Override
                public void onError(FacebookException e) {
                    Toast.makeText(getActivity(), "Problem connecting to Facebook", Toast.LENGTH_SHORT).show();
                }
            });
        }
    
        public void requestUserProfile(LoginResult loginResult){
            GraphRequest.newMeRequest(
                    loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(JSONObject me, GraphResponse response) {
                            if (response.getError() != null) {
                                // handle error
                                Log.e(TAG, "Error logging onto facebook: " + response.getError());
                            } else {
                                try {
                                    String email = response.getJSONObject().get("email").toString();
                                    Log.e("Result", email);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                String id = me.optString("id");
                                // send email and id to your web server
                                Log.e("Result1", response.getRawResponse());
                                Log.e("Result", me.toString());
                            }
                        }
                    }).executeAsync();
        }
    


    THIRD
        private void setupFacebookLoginButton() {
            //Customise Facebook login button
            LoginButton loginButton = (LoginButton) rootView.findViewById(R.id.login_button);
            loginButton.setFragment(this);
            //loginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday"));
            loginButton.setReadPermissions("email");
    
    
            // Callback registration
            //final CallbackManager callbackManager = CallbackManager.Factory.create();
            loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {
                    Log.d(TAG, "login success");
                    // App code
                    GraphRequest request = GraphRequest.newMeRequest(
                            loginResult.getAccessToken(),
                            new GraphRequest.GraphJSONObjectCallback() {
                                @Override
                                public void onCompleted(JSONObject object, GraphResponse response) {
                                    Log.d(TAG, response.toString());
                                    try {
                                        String email = response.getRequest().getGraphObject().getString("email");
                                        Log.d(TAG, "Users email: " + email);
                                    } catch (JSONException e) {
                                        Log.e(TAG, "Unable to get email", e);
                                    }
                                    //String email = user..getProperty("email").toString();
    
                                }
                            });
                    Bundle parameters = new Bundle();
                    //parameters.putString("fields", "id,name,email,gender, birthday");
                    parameters.putString("fields", "email");
                    request.setParameters(parameters);
                    request.executeAsync();
                }
    
                @Override
                public void onCancel() {
                    Log.d(TAG, "Facebook login cancelled");
                }
    
                @Override
                public void onError(FacebookException exception) {
                    Log.e(TAG, "Facebook login error", exception.getCause());
                }
            });
        }
    



    Like I said, with all 3 of these samples, I can Login to Facebook, but after I login and click "OK" on Facebooks login screen, it returns back to my Fragment, but none of the Log data gets displayed in Logcat. So its as if I'm logging in, but its not hooking up to my return code.

    I dunno. This is my first attempt and I'm doing it on my own so haven't got the foggiest what I'm doing. And the docs are very little help.

    If anyone can help, It'd be very much appreciated.

    Thanks.


  • Registered Users, Registered Users 2 Posts: 33 driveshark


    I'd really need to see your full activity & fragment code to see whats going on, but my guess would be that you're not implementing onActivityResult() since you're not receiving any callback after login. You should implement this method within your activity:

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

    If you have anything on github or similar I'd have a proper look and test it.

    Also, I'm assuming with the above you have already correctly configured a Facebook app via the Facebook app dashboard.


  • Registered Users, Registered Users 2 Posts: 7,893 ✭✭✭The_B_Man


    Hi,

    Never got back to you on this.

    Yes I hadn't implemented the onActivityResult() method.

    (actually I had, but with all the source code I was messing with, I had actually commented it out :o)

    Thanks.


Advertisement