Facebook SDK 3.0 Integration

Has anyone successfully integrated Facebook SDK 3.0 with android? I am getting the error “Cannot call Login Activity with null package”

Thanks.

If I follow the Facebook tutorial as it is to integrate it into android, it works. Which means that if I create a pure java project without cocos2dx, the facebook integration works as expected. If I do the same thing in a cococ2dx project, it crashes. Anyone figured this out?

Hi, did you complete your fb android integration? :slight_smile: i want favour

Do you have any code snippets of how you’re trying to call the Facebook API with cocos2dx?

Hi,
This might help.

Thank you.

`gamier No have not yet been able to do it.

`Daniel
This is the java class that is initializing facebook as soon as it is created

`public class Test0001 extends Cocos2dxActivity{

static private Test0001 instance;
static private String userName;
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    Test0001.instance = this;

    Intent intent = new Intent(this, com.facebook.LoginActivity.class);
    startActivityForResult(intent, 1);

     Session.openActiveSession(this, true, new Session.StatusCallback() {

          // callback when session changes state
          `Override

public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {

// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

// callback after Graph API response with user object
`Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// TextView welcome = (TextView) findViewById(R.id.welcome);
// welcome.setText("Hello " + user.getName() + “!”);
Log.i(“tag”,"username is "+user.getName());
}
}
});
}
}
});
}

static {
     System.loadLibrary("game");
}

`Override

public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
}@

@Sameer I need to initialize facebook. I have figured out hot to make JNI calls.

Hi,
I have implement this in Cocos2dxHelper by making new method.it is working fine.
No need to init facebook object.well i am also working on facebook3 to optimize it.

if need then i can post my code here.

Thank you.

`nidhi i had implemented Fb integration with android and it is working i also implemented it in cocos2dx i have a class that is using JNI to make calls…Butt am getting errors :frowning:

`sameer please post your code.

`Sameer If you could post your code, that would really help :slight_smile: I am using Facebook SDK 3.0

`Gamier can u post source code where you are getting errors? And what are the errors?

Hi All,

In $coco2dxHome/cocos2dx/platform/android/application.cpp
add new method
void CCApplication::postMsgOnFacebook(char *msg){

JniMethodInfo minfo;

if(JniHelper::getStaticMethodInfo(minfo,
“org/cocos2dx/lib/Cocos2dxHelper”,
“postMsgOnFacebook”,
“(Ljava/lang/String;)V”))
{
jstring StringArg1 = minfo.env~~>NewStringUTF;
minfo.env~~>CallStaticVoidMethod(minfo.classID, minfo.methodID, StringArg1);
minfo.env~~>DeleteLocalRef;
minfo.env~~>DeleteLocalRef(minfo.classID);
}
}

On any menuButton Click call facebook api
CCApplication::sharedApplication()->postMsgOnFacebook(
((char *) “fb string post”));

In cocos2dxHelper.java,

private static final List PERMISSIONS = Arrays
.asList(“publish_actions”);
private static final String PENDING_PUBLISH_KEY = “pendingPublishReauthorization”;
private static boolean pendingPublishReauthorization = false;
//we need to implement the hanlder due to game run in thread,
public static void postMsgOnFacebook(final String msg) {

Log.d(“FBMSG”, msg);
Message fbMsg = new Message();
fbMsg.arg1 = FACEBOOK_LOGIN;
fbMsg.obj = msg;
facebookHandler.sendMessage(fbMsg);

}

static Handler facebookHandler = new Handler() {
public void handleMessage(final Message msg) {

if (msg.arg1 FACEBOOK_LOGIN) {

            if (isNetworkAvailable()) {

                me.removeDialog(DIALOG\_FACEBOOK\_PROGRESS);
                me.showDialog(DIALOG\_FACEBOOK\_PROGRESS);
                Session.openActiveSession(me, true,
                        new Session.StatusCallback() {

                            // callback when session changes state
                            @Override
                            public void call(Session session,
                                    SessionState state, Exception exception) {
                                if (session.isOpened()) {

                                    // make request to the /me API
                                    Request.executeMeRequestAsync(
                                            session,
                                            new Request.GraphUserCallback() {

                                                // callback after Graph API
                                                // response with user object
                                                @Override
                                                public void onCompleted(
                                                        GraphUser user,
                                                        Response response) {
                                                    if (user != null) {
                                                        Log.d("Complete",
                                                                "ok");
                                                        publishStory("Dragon Boat Racing");
                                                    } else {

                                                        me.dismissDialog(DIALOG\_FACEBOOK\_PROGRESS);
                                                        Log.d("Complete",
                                                                "ELSE");

                                                    }
                                                }

                                            }

                                    );
                                }
                            }
                        });
                Log.d("postMsgOnFacebook", "ok1");
            } else {
                Log.d("No", "NETWORK");
                Toast.makeText(me.getApplicationContext(),
                        R.string.no\_networ\_error, Toast.LENGTH\_LONG).show();
            }

        }
    };
};

public static void publishStory(String msg) {
    Log.d("Publish", "story");
    Log.d("Publish", "" + msg);
    Session session = Session.getActiveSession();

    if (session != null) {
        Log.d("Publish", "session working");
        // Check for publish permissions
        List\<String\> permissions = session.getPermissions();
        if (!isSubsetOf(PERMISSIONS, permissions)) {
            pendingPublishReauthorization = true;
            Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(
                    me, PERMISSIONS);
            session.requestNewPublishPermissions(newPermissionsRequest);
            return;
        }

        // /taking screen shots
        //Bitmap screenShot = takeScreenShot(me);
        //Bitmap screenShot =  SavePixels(0,0,1280,752,((Cocos2dxActivity)me).getgl10());
        //savePic(screenShot, "/sdcard/temp.png");

// Log.d(“SCREEN”, “taken”);
// if(screenShotnull)
// Log.d(“BITMAP”,“NULL”);

Bundle postParams = new Bundle();
postParams.putString(“name”, msg);
//ByteArrayOutputStream stream = new ByteArrayOutputStream();
//screenShot.compress(Bitmap.CompressFormat.PNG, 100, stream);
//byte[] byteArray = stream.toByteArray();

FileInputStream fileStream = null;
byte[] byteArray = null;
try {
Log.e(TAG, “Main Application Package Name ::”me.getApplicationContext.getPackageName);
fileStream = new FileInputStream.getPackageName
“/DB_Screenshot.png”);
byteArray = IOUtils.toByteArray(fileStream);
// Do something useful to the data
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
IOUtils.closeQuietly(fileStream);
fileStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Log.d(“SCREEN”, “bytearray”);
postParams.putByteArray(“picture”, byteArray);
Request.Callback callback = new Request.Callback() {
public void onCompleted(Response response) {
Log.d(“publishComplete”, “ok”);
me.dismissDialog(DIALOG_FACEBOOK_PROGRESS);

FacebookRequestError error = response.getError();
if (error != null) {
Log.d(“TAG”, “” + error.getErrorMessage());
Log.d(“TAG”, “” + error.getErrorCode());
Toast.makeText(me.getApplicationContext(),
R.string.com_facebook_post_image_error,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(me.getApplicationContext(),
R.string.com_facebook_post_image_success,
Toast.LENGTH_LONG).show();

String postId = null;
try {
JSONObject graphResponse = response
.getGraphObject().getInnerJSONObject();
postId = graphResponse.getString(“id”);
} catch (JSONException e) {
Log.i(“TAG”, “JSON error” + e.getMessage());
} catch (Exception e) {
Log.i(“TAG”, “” + e.getMessage());
} finally {
if (postId != null) {
// Toast.makeText(me.getApplicationContext(),
// R.string.com_facebook_post_image_success,
// Toast.LENGTH_LONG).show();
Log.d(“IMAGE”, “POST”);

}
}

}

}
};

Request request = new Request(session, “me/photos”, postParams,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}

}

This call code that i have done,please facebook3 implementation for developer facebook site like change need in manifest file
please feel free to any anything, because i have also struggle a lot for this.

Thank you.

@nidhi here is the link where i posted my error http://www.cocos2d-x.org/boards/6/topics/21894

and now i have different errors…Here is my error log :
01-29 02:28:24.495: E/AndroidRuntime(13488): FATAL EXCEPTION: main
01-29 02:28:24.495: E/AndroidRuntime(13488): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.mons.project/org.mons.project.GetSocial}: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=org.mons.project }
01-29 02:28:24.495: E/AndroidRuntime(13488): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
01-29 02:28:24.495: E/AndroidRuntime(13488): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
01-29 02:28:24.495: E/AndroidRuntime(13488): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
01-29 02:28:24.495: E/AndroidRuntime(13488): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
01-29 02:28:24.495: E/AndroidRuntime(13488): at android.os.Handler.dispatchMessage(Handler.java:99)
01-29 02:28:24.495: E/AndroidRuntime(13488): at android.os.Looper.loop(Looper.java:130)
01-29 02:28:24.495: E/AndroidRuntime(13488): at android.app.ActivityThread.main(ActivityThread.java:3691)
01-29 02:28:24.495: E/AndroidRuntime(13488): at java.lang.reflect.Method.invokeNative(Native Method)
01-29 02:28:24.495: E/AndroidRuntime(13488): at java.lang.reflect.Method.invoke(Method.java:507)
01-29 02:28:24.495: E/AndroidRuntime(13488): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
01-29 02:28:24.495: E/AndroidRuntime(13488): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
01-29 02:28:24.495: E/AndroidRuntime(13488): at dalvik.system.NativeStart.main(Native Method)
01-29 02:28:24.495: E/AndroidRuntime(13488): Caused by: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=org.mons.project }
01-29 02:28:24.495: E/AndroidRuntime(13488): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1409)
01-29 02:28:24.495: E/AndroidRuntime(13488): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1379)
01-29 02:28:24.495: E/AndroidRuntime(13488): at android.app.Activity.startActivityForResult(Activity.java:2833)
01-29 02:28:24.495: E/AndroidRuntime(13488): at android.app.Activity.startActivity(Activity.java:2959)
01-29 02:28:24.495: E/AndroidRuntime(13488): at org.mons.project.GetSocial.onCreate(GetSocial.java:67)
01-29 02:28:24.495: E/AndroidRuntime(13488): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-29 02:28:24.495: E/AndroidRuntime(13488): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
01-29 02:28:24.495: E/AndroidRuntime(13488): … 11 more

This error is occur most of when we dont add activity in manifest…But i have added activity but same error is occurring…:confused:

Hi,
I have try to do in old facebook lib and it is working fine
In cocos2dxHelper
public static int FACEBOOK_LOGIN = 0;
public static int FACEBOOK_IMG_POST = 4;
public static int FACEBOOK_POST = 0;
static Facebook facebook;
static Handler facebookHandler = new Handler() {
public void handleMessage(final Message msg) {

if (msg.arg1 FACEBOOK_LOGIN) {

            if (isNetworkAvailable()) {
                String message = msg.obj.toString();
                Log.d("message", message);
                facebook = new Facebook("111055529057881");
                if (facebook.isSessionValid()) {
                    Log.d("Loged", "IN");
                    postOnWall(message);
                } else {
                    Log.d("Loged", "NOT");
                    String[] permission = new String[] { "publish\_stream, publish\_actions" };
                    facebook.authorize(me, permission, new LoginListner(
                            message));
                }
            } else {
                Log.d("No", "NETWORK");
                showToast(R.string.no\_networ\_error);
            }

        } else if (msg.arg1  FACEBOOK\_IMG\_POST) {

Log.d(“POST COPLETE”, “ok”);
Log.d(“msg.arg2”, “” + msg.arg2);
if (msg.arg2 0) {
showToast(R.string.com_facebook_post_image_error);
} else {
showToast(R.string.com_facebook_post_image_success);
}
}
};
};
public static class LoginListner implements DialogListener {

    String msg;

    public LoginListner(String msg) {
        this.msg = msg;
    }

    @Override
    public void onComplete(Bundle values) {
        Log.d("Login", "Complete=" + msg);
        postOnWall(msg);
    }

    @Override
    public void onFacebookError(FacebookError e) {
        Log.d("Login", "error");
        showToast(R.string.login\_fb\_error);
    }

    @Override
    public void onError(DialogError e) {
        Log.d("Login", "dialogerror=" + e);
        showToast(R.string.login\_fb\_error);
    }

    @Override
    public void onCancel() {
        Log.d("Login", "Cancel");
        showToast(R.string.login\_fb\_cancel);
    }

}

public static void postOnWall(final String msg) {
    Log.d("MSG", msg);
    Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {
            boolean isPosted = false;
            try {
                String response = facebook.request("me");
                Bundle parameters = new Bundle();
                parameters.putString("name",msg);
                FileInputStream fileStream = null;
                byte[] byteArray = null;
                try {
                    Log.e(TAG, "Main Application Package Name :: "+me.getApplicationContext().getPackageName());
                    fileStream = new FileInputStream("/data/data/"+ me.getApplicationContext().getPackageName() +"/DB\_Screenshot.png");
                    byteArray = IOUtils.toByteArray(fileStream);                 
                    // Do something useful to the data
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {                   
                        IOUtils.closeQuietly(fileStream);
                        fileStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }           
                if(fileStream!=null){
                    parameters.putByteArray("picture", byteArray);
                }

                response = facebook.request("me/photos", parameters, "POST");
                Log.d("Tests", "got response: " + response);
                if (response  null || response.equals(“”)

|| response.equals(“false”)) {
Log.v(“Error”, “Blank response”);
isPosted = false;
} else {
isPosted = true;
}
} catch (Exception e) {
e.printStackTrace();
isPosted = false;
}

// `dev sending call back to handler with posted result
// 1== image is postes , 0 image is not posted
Message msg = new Message();
msg.arg1 = FACEBOOK_IMG_POST;
if (isPosted)
msg.arg2 = 1;
else
msg.arg2 = 0;

            facebookHandler.sendMessage(msg);
        }
    });

    thread.start();

}

In Cocos2dxActivity,

`Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(“REQUEST”,“”+requestCode);
Log.d(“RES”,“”+resultCode);
Cocos2dxHelper.facebook.authorizeCallback(requestCode, resultCode, data);
}

If need then i can upload old facebook sdk here.

Thank you.

Hi sameer,

I dont know about facebook3…I m doing integration with facebook android sdk if you have codes then please post it.

Hi,

I can’t send the old facebook sdk,as i am working for company so please try to find on internet.

Thank you.

So it turns out that the integration works as long as I call a void java function from c++. The minute I try to call a function that returns a string, it crashes.

same here …

Nidhi Ajwani wrote:

So it turns out that the integration works as long as I call a void java function from c++. The minute I try to call a function that returns a string, it crashes.
Hi,
Can please post all code here including Cocos2dxHelper.java,CCApplication.cpp

Thank you.

Hi Sameer,
Sorry for the late reply. I figured it out. I was trying to return a string whose value was NULL as the facebook call had not been completed. Any idea how we can call c*+ form java? I tried what they say here http://www.cocos2d-x.org/projects/cocos2d-x/wiki/How_to_use_jni but I am getting errors saying that the function is being redefined. What I need to do is pass back the username from java back to c*+ once the facebook callback is complete. I know that I can call a function after a certain amount of time from c++ to java but this will not be correct as the network processing might take time and I will still get a null parameter.

Thanks,
Nidhi

`Gamier what version of the sdk are u using? Are u using JniHelper? It really solves things down. From the looks, u are trying to pass a string a string as an argument to the function, correct? This is my JNI call to a static function that takes zero parameters and returns a string

`JniMethodInfo t;
// get method ‘getResolution’ which returns int array ‘()[I’ from java package ‘com.mygame’ & ‘MyGame’ class
if (JniHelper::getStaticMethodInfo(t,
“com/WBS/Test0001/Test0001”,
“LoginFB”,
“()Ljava/lang/String;”))
{

jstring stg = (jstring)t.env~~>CallStaticObjectMethod;
const char *name = t.env~~>GetStringUTFChars(stg,NULL);
CCLog(“name is %s”,name);

}@

From what i understand of JNI, u need to pass the string as a parameter to this function call “t.env->CallStaticObjectMethod(t.classID, t.methodID);” I will look it up and get back on that.

@gamier Have a look at this http://blog.csdn.net/kafei_kings/article/details/8106744

Its in chinese but if u look at the code, u will understand how to pass parameters.