Kamil
Kamil

Reputation: 13931

Null pointer exception on com.facebook.Session object

When I run this:

Session session = Session.getActiveSession();

if (!session.isOpened() && !session.isClosed())
{
    session.openForRead(new Session.OpenRequest(this)
        .setPermissions(Arrays.asList("public_profile"))
        .setCallback(statusCallback));
}
else 
{
    Session.openActiveSession(getActivity(), this, true, statusCallback);
}

it causes NullPointer Exception:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.facebook.Session.isOpened()' on a null object reference


My code is in onClick() button handler.

I have all this in a Fragment, not in Activity.

Did I missed something?

Upvotes: 0

Views: 550

Answers (3)

Yi-Ping Shih
Yi-Ping Shih

Reputation: 1092

According to the document,

getActiveSession() returns the current active Session, or null if there is none.

So just modify your if statement to handle the situation:

Session session = Session.getActiveSession();
if (session != null && (!session.isOpened() && !session.isClosed()))
{
    session.openForRead(new Session.OpenRequest(this)
    .setPermissions(Arrays.asList("public_profile"))
    .setCallback(statusCallback));
}
else 
{
    Session.openActiveSession(getActivity(), this, true, statusCallback);
}

Upvotes: 3

Iqbal S
Iqbal S

Reputation: 1154

If you have no session initialized then you may need to go to ConnectPlugin.java, on facebook plugin, and change the below code in initialize method.

    Session session = new Session.Builder(cordova.getActivity()).setApplicationId(applicationId).build();
        if (session.getState() == SessionState.CREATED_TOKEN_LOADED) {
        Session.setActiveSession(session);
// Create the request
        Session.OpenRequest openRequest = new Session.OpenRequest(cordova.getActivity()); 

by the below one:

// Open a session if we have one cached Session session = new Session.Builder(cordova.getActivity()).setApplicationId(applicationId).build();
Session.setActiveSession(session);
if (session.getState() == SessionState.CREATED_TOKEN_LOADED) {
// Create the request Session.
OpenRequest openRequest = new Session.OpenRequest(cordova.getActivity());

This shall fix your problem.

Upvotes: 0

Iqbal S
Iqbal S

Reputation: 1154

After getting the session if it is null then, restore the session from cache using the below code:

Session session = Session.getActiveSession();

if(session==null){ 
// try to restore from cache 
session = Session.openActiveSessionFromCache(getActivity());
}

Upvotes: 0

Related Questions