Facebook onCompleted Email java.lang.NullPointerException
Asked Answered
P

2

9

I'm able to get all those things as shown in my code below, but unable to retrieve email from the user profile.

What can I do for this?

Any kind of help will be appreciated.

Earlier I was using this source to get details of Facebook user and was fetching data (including Email) without any trouble:

public class MainActivity extends Activity {
    private Session.StatusCallback sessionStatusCallback;
    private Session currentSession;

    private Button login;
    private Button logout;
    private Button publishButton;

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView) findViewById(R.id.textView);

        // create instace for sessionStatusCallback
        sessionStatusCallback = new Session.StatusCallback() {

            @Override
            public void call(Session session, SessionState state,
                             Exception exception) {
                onSessionStateChange(session, state, exception);

            }
        };

        login = (Button) findViewById(R.id.loginButton);
        login.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                connectToFB();                
            }
        });

        logout = (Button) findViewById(R.id.logoutButton);
        logout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (currentSession != null) {
                    currentSession.closeAndClearTokenInformation();
                    ...
                }
            }
        });

        // publish button
        publishButton = (Button) findViewById(R.id.publishButton);
        publishButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                publishStory();

            }
        });

    }

    public void connectToFB() {

        List<String> permissions = new ArrayList<String>();
        permissions.add("publish_actions");

        currentSession = new Session.Builder(this).build();
        currentSession.addCallback(sessionStatusCallback);

        Session.OpenRequest openRequest = new Session.OpenRequest(
                MainActivity.this);
        openRequest.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
        openRequest.setRequestCode(Session.DEFAULT_AUTHORIZE_ACTIVITY_CODE);
        openRequest.setPermissions(permissions);
        currentSession.openForPublish(openRequest);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (currentSession != null) {
            currentSession
                    .onActivityResult(this, requestCode, resultCode, data);
        }
    }

    private void onSessionStateChange(Session session, SessionState state,
                                      Exception exception) {
        if (session != currentSession) {
            return;
        }

        if (state.isOpened()) {
            // Log in just happened.
            Toast.makeText(getApplicationContext(), "session opened",
                    Toast.LENGTH_SHORT).show();

            Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
                @Override
                public void onCompleted(GraphUser user, Response response) {
                    String fbId = user.getId();
                    String fbName = user.getName();
                    String gender = user.asMap().get("gender").toString();
                    String email = user.asMap().get("email").toString();
                    String first = user.asMap().get("first_name").toString();
                    String last = user.asMap().get("last_name").toString();

                    textView.setText("Id: " + fbId + ", Name: " + fbName + ", Gender: " + gender + ", EmailID: " + email + ", First: " + first + ", Last: " + last);
                }
            });

        } else if (state.isClosed()) {
            // Log out just happened. Update the UI.
            Toast.makeText(getApplicationContext(), "session closed",
                    Toast.LENGTH_SHORT).show();
        }
    }

    public void publishStory() {
        ....
    }

}

And now I am using same code in one of my project, but always getting:

E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException 
at c.o.m.MainActivity$5.onCompleted(MainActivity.java:262)
at com.facebook.Request$1.onCompleted(Request.java:303)
at com.facebook.Request$4.run(Request.java:1726)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4921)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)

At this line, I am getting NPE:

 String email = user.asMap().get("email").toString();

Code:

public class MainActivity extends Activity {

    Button btnFBLogin, btnGPLogin;

    private Session.StatusCallback sessionStatusCallback;
    private Session currentSession;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.screen_layout);

        sessionStatusCallback = new Session.StatusCallback() {

            @Override
            public void call(Session session, SessionState state,
                             Exception exception) {
                onSessionStateChange(session, state, exception);

            }
        };

        btnFBLogin = (Button) findViewById(R.id.loginFB);
        btnFBLogin.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                connectToFB();
            }
        }); 

    }

    public void connectToFB() {

        List<String> permissions = new ArrayList<String>();
        permissions.add("publish_actions");

        currentSession = new Session.Builder(this).build();
        currentSession.addCallback(sessionStatusCallback);

        Session.OpenRequest openRequest = new Session.OpenRequest(
                MainActivity.this);
        openRequest.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
        openRequest.setRequestCode(Session.DEFAULT_AUTHORIZE_ACTIVITY_CODE);
        openRequest.setPermissions(permissions);
        currentSession.openForPublish(openRequest);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (currentSession != null) {
            currentSession
                    .onActivityResult(this, requestCode, resultCode, data);
        }
    }

    private void onSessionStateChange(Session session, SessionState state,
                                      Exception exception) {
        if (session != currentSession) {
            return;
        }

        if (state.isOpened()) {
            // Log in just happened.
            Toast.makeText(getApplicationContext(), "session opened",
                    Toast.LENGTH_SHORT).show();

            Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
                @Override
                public void onCompleted(GraphUser user, Response response) {
                    String fbId = user.getId();
                    String fbName = user.getName();
                    String gender = user.asMap().get("gender").toString();
                    String email = user.asMap().get("email").toString();
                    String first = user.asMap().get("first_name").toString();
                    String last = user.asMap().get("last_name").toString();

                    Toast.makeText(MainActivity.this, "EmailId:- "+email, Toast.LENGTH_LONG).show();
                }
            });

        } else if (state.isClosed()) {
            // Log out just happened. Update the UI.
            Toast.makeText(getApplicationContext(), "session closed",
                    Toast.LENGTH_SHORT).show();
        }
    }
}

What could be the reason? Why its happening?

Phineas answered 22/5, 2015 at 5:45 Comment(5)
how bad.. what's wrong here ?Phineas
Log.i("fb", "fb user: " + user.toString()); why are you doing this ? does you session exists ?Forestation
@Sun: probably calling toString() on null so try using String email = user.asMap().get("email")Motherly
it seems like you are using deprecated facebook sdk. first upgrade it to latest.Mcintire
You can not pass "publish_actions" at a time of login. Previously you can send but with newer fb sdk, it's not supported. And you need to pass these two "public_profile", "email".Angadreme
O
0

Sometime it might be happen that User not set their Email Id in their Profile which are you getting in Your Facebook Login Via Android so that throws Error like Null Pointer Exception.

So You should have to check before using the Email Variable after fetching from Login that it is null or not Such as :

String email ="";
if(user.asMap().get("email") != null){
 email = user.asMap().get("email").toString();
}
Occasionalism answered 22/5, 2015 at 6:13 Comment(2)
like i wrote in my earlier example i was getting Email as well, and i am using same account to loginPhineas
Ya Sure but as i checked out your above code and you missed to checked that If mail id exist or not. So Now using this code you not have any issue related to null pointer exception in your above suggested question line : String email = user.asMap().get("email").toString();Occasionalism
T
0

You need to add "email" to the list of permissions you're requiring, otherwise the email will always be null. I don't know what version of the sdk you're using. With the last one you can write:

Collection<String> mPermissions = new ArrayList<>();
mPermissions.add("email");
LoginManager mLoginManager = LoginManager.getInstance();
CallbackManager mCallbackManager = CallbackManager.Factory.create();
FbCallback fbCallback = new FbCallback(this);
mLoginManager.registerCallback(mCallbackManager, fbCallback);
[...]
mLoginManager.logInWithReadPermissions(this, mPermissions);

By the way...remember that the user can revoke the permission or cannot grant it during the login.

Twirp answered 15/7, 2015 at 14:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.