5

i just learned about facebook SDK on android. I already search on stackoverflow and facebook developer guide for login, but i still stuck when get profile data from facebook sdk. i try implement solution from : unable get profile and Get email, but still stuck.

There is my code :

    public class HomeLoginActivity extends Activity {
   LoginButton btnFacebook;
    CallbackManager callbackManager = CallbackManager.Factory.create();
    ProfileTracker profTrack;
    AccessTokenTracker accessTokenTracker;
    TextView welcomeText;
    FacebookCallback<LoginResult> mFacebookCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(this.getApplicationContext());
        setContentView(R.layout.activity_home_login);
        welcomeText = (TextView) findViewById(R.id.welcome_id);
        accessTokenTracker = new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(
                    AccessToken oldAccessToken,
                    AccessToken currentAccessToken) {
                // App code
                Log.d("current token", "" + currentAccessToken);

                //}
            }
        };
        profTrack = new ProfileTracker() {
            @Override
            protected void onCurrentProfileChanged(
                    Profile oldProfile,
                    Profile currentProfile) {
                // App code
                Log.d("current profile", "" + currentProfile);
                welcomeText.setText(constructWelcomeMessage(currentProfile));
            }

        };
        mFacebookCallback = new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                AccessToken accessToken = loginResult.getAccessToken();
                Profile profile = Profile.getCurrentProfile();
                welcomeText.setText(constructWelcomeMessage(profile));

                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(
                                    JSONObject object,
                                    GraphResponse response) {
                                // Application code
                                try {
                                    String id=object.getString("id");
                                    String name=object.getString("name");
                                    String email=object.getString("email");
                                    String gender=object.getString("gender");
                                    Stringbirthday=object.getString("birthday");

                                    //do something with the data here
                                } catch (JSONException e) {
                                    e.printStackTrace(); 
                                }
                            }
                        });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email,gender,birthday");
                request.setParameters(parameters);
                request.executeAsync();
            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onError(FacebookException e) {

            }
        };

        accessTokenTracker.startTracking();
        profTrack.startTracking();

        //Button Facebook
        btnFacebook = (LoginButton) findViewById(R.id.btnFacebook);
        btnFacebook.setReadPermissions("public_profile", "user_friends");
        btnFacebook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            LoginManager.getInstance().logInWithReadPermissions((Activity) v.getContext(),Arrays.asList("public_profile", "user_friends"));
            }
        });
        btnFacebook.registerCallback(callbackManager, mFacebookCallback);

    }
    // ennd on create
    private String constructWelcomeMessage(Profile profile) {
        StringBuffer stringBuffer = new StringBuffer();
        if (profile != null) {
            stringBuffer.append("Welcome " + profile.getName());
        }
        else {
            stringBuffer.append("NULL Profile");
        }
        return stringBuffer.toString();
    }


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

    }
    @Override
    public void onResume() {
        super.onResume();
        AccessToken.getCurrentAccessToken();
        Log.d("resume current token", "" + AccessToken.getCurrentAccessToken());
        Profile.fetchProfileForCurrentAccessToken();
    }

    @Override
    public void onStop() {
        super.onStop();
        profTrack.stopTracking();
        accessTokenTracker.stopTracking();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        accessTokenTracker.stopTracking();
        profTrack.stopTracking();
    }
}

and there is my log cat :

 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
            at com.twiscode.gimme.HomeLoginActivity$3$1.onCompleted(HomeLoginActivity.java:100)
            at com.facebook.GraphRequest$1.onCompleted(GraphRequest.java:298)
            at com.facebook.GraphRequest$5.run(GraphRequest.java:1246)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Community
  • 1
  • 1
  • thanks, i already post my logcat about this error. – Bagus Kristomoyo Kristanto Apr 28 '15 at 07:15
  • You are trying to call `getString` on a null object in your `onCompleted` callback, which probably means that you don't have an active Facebook session. – Gerstmann Apr 28 '15 at 07:22
  • yes, i try to get String id=object.getString("id"); after complete graph request from facebook SDK. Although, i deleted the graph request and just use profile tracker and accesstoketracker, when i call Profile.getCurrentProfile(), the Profile still NULL. On facebook SDK 4.0, facebook delete the session and chane to acesstoken, if i didn't login, why the function of onsuccess inside login result called? i stuck on this, success login but can't get data user profile – Bagus Kristomoyo Kristanto Apr 28 '15 at 07:28
  • Does the `GraphResponse` contain any hints on what might've went wrong? – Gerstmann Apr 28 '15 at 07:34
  • No, just explain that the return was null. it's null pointer exception in both of JSONObject or GraphResponse – Bagus Kristomoyo Kristanto Apr 28 '15 at 07:37

4 Answers4

5

Try this sample code to get profile info

loginButton.registerCallback(callbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {
                    // App code

                    // login ok get access token
                    GraphRequest request = GraphRequest.newMeRequest(
                            AccessToken.getCurrentAccessToken(),
                            new GraphRequest.GraphJSONObjectCallback() {
                                @Override
                                public void onCompleted(JSONObject object,
                                        GraphResponse response) {

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

                                        System.out
                                                .println("AccessToken.getCurrentAccessToken()"
                                                        + AccessToken
                                                                .getCurrentAccessToken()
                                                                .toString());
                                        Profile.getCurrentProfile().getId();
                                        Profile.getCurrentProfile().getFirstName();
                                        Profile.getCurrentProfile().getLastName();
                                        Profile.getCurrentProfile().getProfilePictureUri(50, 50);
                                        //String email=UserManager.asMap().get(“email”).toString();
                                    }
                                }
                            });
                    request.executeAsync(); 
                /*  Bundle parameters = new Bundle();
                    parameters
                            .putString("fields",
                                    "id,firstName,lastName,name,email,gender,birthday,address");
                    request.setParameters(parameters);



                    Intent loginintent = new Intent(getActivity(),
                            EditProfile.class);
                    startActivity(loginintent);
                    System.out.println("XXXX " + getId());
                 */
                    makeJsonObjReq();
                }

                @Override
                public void onCancel() {
                    // App code
                }

                @Override
                public void onError(FacebookException exception) {
                    // App code
                }

            });

    return view;
Prabha1
  • 233
  • 1
  • 4
  • 22
1

I was facing the same error and finally found the solution. Basically you have to know first what is causing this crash/NullPointerException. So to find out what is causing this exception, make your onComplete block of code look like below:

                        GraphRequest request = GraphRequest.newMeRequest(
                            loginResult.getAccessToken(),
                            new GraphRequest.GraphJSONObjectCallback() {
                                @Override
                                public void onCompleted(
                                        JSONObject object,
                                        GraphResponse response) {
                                    Log.v("LoginActivity Response ", response.toString());
                                }
                            });

Now, run your app and try logging in using the FB button. Keep checking your logcat and soon you will see a line like below:

V/LoginActivity Response: {Response:  responseCode: 200, graphObject: {"id":"10206735777938523","name":"Rohit Paniker","email":"rohit.paniker.1990@gmail.com","gender":"male"}, error: null}

I was using the "age" permission which was causing the NullPointerException in ID, Name, Email and all permissions which i got to know from the above logcat output. As per the output i understood why the crash was happening and I removed the object.getString("age") and ran the app again, worked perfectly without crash and I got all data from ID to Name and email!

rohitpaniker
  • 695
  • 1
  • 7
  • 25
0

See my working code below to get profile details FB SDK 4

    //Initialize Facebook SDK
    FacebookSdk.sdkInitialize(getApplicationContext());

    //if the facebook profile is changed, below code block will be called
    profileTracker = new ProfileTracker() {
        @Override
        protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {

            if(currentProfile != null){
                fbUserId = currentProfile.getId();

                if(!sharedPreferences.contains("UserName")){
                    editor.putString("UserName",currentProfile.getFirstName()+" "+currentProfile.getLastName());
                }
                if(!sharedPreferences.contains("FbId")){
                    editor.putString("FbId",currentProfile.getId());
                }
                if(!sharedPreferences.contains("ProfilePicture")){
                    editor.putString("ProfilePicture",currentProfile.getProfilePictureUri(100,100).toString());
                }

                editor.commit();
            }
        }
    };

    //when new fb user logged in , below code block will be called
    AccessTokenTracker accessTokenTracker = new AccessTokenTracker() {
        @Override
        protected void onCurrentAccessTokenChanged(AccessToken accessToken, AccessToken accessToken2) {
            System.out.println("acesstoken trackercalled");
        }
    };



    //set layout resource
    setContentView(R.layout.activity_login);

    //fb login button
    loginButton = (LoginButton) findViewById(R.id.connectWithFbButton);

    //set fb permissions
    loginButton.setReadPermissions(Arrays.asList("public_profile,email"));

    //call the login callback manager
    callbackManager = CallbackManager.Factory.create();
    LoginManager.getInstance().registerCallback(callbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {

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

                        if(!sharedPreferences.contains("UserName")){
                            editor.putString("UserName",profile.getFirstName()+" "+profile.getLastName());
                        }
                        if(!sharedPreferences.contains("FbId")){
                            editor.putString("FbId",profile.getId());
                        }
                        if(!sharedPreferences.contains("ProfilePicture")){
                            editor.putString("ProfilePicture",profile.getProfilePictureUri(20,20).toString());
                        }
                        editor.commit();
                    }



                    goToNewActivity();
                }

                @Override
                public void onCancel() {
                }

                @Override
                public void onError(FacebookException e) {

                }


            });
Deepika
  • 516
  • 4
  • 6
0

Please try with this code :

LoginManager.getInstance().logInWithReadPermissions(Activity.this, Arrays.asList("public_profile","email"));

                LoginManager.getInstance().registerCallback(callbackManager,
                        new FacebookCallback<LoginResult>() {

                            public void onSuccess(LoginResult loginResult) {
                                if (AccessToken.getCurrentAccessToken() != null) {

    Log.e("idfb",""+loginResult.getAccessToken().getUserId());

    GraphRequest request = GraphRequest.newMeRequest(
            loginResult.getAccessToken(),
            new GraphRequest.GraphJSONObjectCallback() {
              @Override
              public void onCompleted(JSONObject object, GraphResponse response) {
                // Application code
                try {
                  Log.i("Response",response.toString());

                  String email = response.getJSONObject().getString("email");
                  String name = response.getJSONObject().getString("name");
                  String id = response.getJSONObject().getString("id");

                 String imgUrl = "https://graph.facebook.com/" + id + "/picture?type=large";

                  Log.i("Login" + "Email", "");
                  Log.i("Login"+ "FirstName", name);
                  Log.i("Login" + "Id", id);



                } catch (JSONException e) {
                  e.printStackTrace();
                  Log.e("errorfb",""+e);
                }
              }
            });
    Bundle parameters = new Bundle();
    parameters.putString("fields", "id,email,name,link");
    request.setParameters(parameters);
    request.executeAsync();

                            }

                           }
                           @Override
                            public void onCancel() {

                            }
                            @Override
                            public void onError(FacebookException exception) {

                            }
                        });
Diwakar Singh
  • 267
  • 3
  • 12
  • While this code may answer the question, providing additional context regarding *how* and *why* it solves the problem would improve the answer's long-term value. – Alexander Jul 23 '18 at 09:33