Integrate your GWT app with Facebook in 4 easy steps

Step 1: Register you app with Facebook.

Sign in to Facebook using your standard credentials. Navigate to http://www.facebook.com/developers/ and click “Set Up New Application.”


Enter a name for your application.


Make note of your API Key. You will need this later. You can come back to this page any time to get it.


Click the “Connect” section on the left. Then enter the base domain name of the website where your application is hosted into the “Connect URL” field. Click the “Save Changes” button at the bottom of the page.


That’s it. You are now the proud developer of a Facebook application, which is required for using Facebook Connect.

Unlike most of the Facebook applications we are used to seeing on the Facebook site, our application does not have an interface for users on the Facebook site. This is something you could certainly add it you need it, but it is not necessary when using Facebook Connect.

Step 2: Add the facebook4gwt JAR to your project .
Go to http://code.google.com/p/facebook4gwt/. Click “downloads” and grab the latest JAR.

Add the JAR to the build path of your GWT project. I’m using an Eclipse project and building it with the Google Eclipse plugin. So I just go to the configure build path dialog, click “Add JARs…” or “Add External JARs…” and select the JAR I just downloaded.

Now add the following line to your module XML file to tell it to include the facebook4gwt module.

<inherits name="com.reveregroup.gwt.facebook4gwt.Facebook4gwt"></inherits>

Step 3: Initialize Facebook Connect.

Facebook Connect needs to be initialized on your web page before using any of its features.

With facebook4gwt, this is accomplished with one simple call:

Facebook.init(YOUR_API_KEY);

This is the API Key that we noted in Step 1 above.

I am making the call in the onModuleLoad() method of my EntryPoint, but you can put it anywhere as long as it comes before you try to use any of its other features.

Step 4: Use the API
Now you’re ready to connect with Facebook. Here are a few examples of what you can do.

Provide a login button
The vast majority of Facebook Connect features require a user to be logged in to Facebook through your site. The API provides a login button that can be placed on your page for a visitor to sign in. It can be used as any other GWT Widget:

loginButton = new LoginButton();
RootPanel.get("facebookLogin").add(loginButton);

Listen for login events
You can register a login listener that is fired whenever a user logs in or out:


Facebook.addLoginHandler(new FacebookLoginHandler() {
public void loginStatusChanged(FacebookLoginEvent event) {

if (event.isLoggedIn()){

statusLabel.setText("Logged in");

} else {

statusLabel.setText("No user logged in");
}

}

});

Get information about a user
The API exposes methods for getting information about the current user or any user given their numeric ID.

In this example we get the current user’s name, status and profile picture. It’s an asynchronous call, so the result is returned to an instance of AsyncCallback.

You also need to specify which information you want the call to fetch for you. These methods use varargs to allow you to easily specify as many items as you need. UserField is an enum with all the possible items.


Facebook.APIClient().users_getLoggedInUser(new AsyncCallback() {
public void onSuccess(FacebookUser result) {
userName.setText(result.getName());

userImage.setUrl(result.getPic());

userInfoPanel.setVisible(true);

}
public void onFailure(Throwable caught) {
userInfoPanel.setVisible(false);
}
}, UserField.NAME, UserField.STATUS, UserField.PIC);


Share with friends
You can add Facebook “Share” buttons to your page in various styles. Again these are just GWT widgets.

new ShareButton(URL_TO_SHARE, TITLE_FOR_POST);

A more advanced option is to post to the user’s wall using templates to customize exactly what information is shown and how. For more on creating facebook feed templates see this blog entry.

The API works like this...

  1. Create an instance of FacebookStory and set the template bundle
    id. You should be able to find the this id with the template you created on
    Facebook's site.
  2. Set the content for your post:

    • Set any key-value pairs of data that your template needs using the
      putData(String, String) method.
    • Add the images, video, mp3 or flash data you want (if any).
    • Set bodyGeneral if desired.

  3. Optionally, configure the dialog with setPrompt() and setDefualtUserMessage().
  4. Finally, call showFeedDialog(). This will display a dialog
    window for your user to confirm the message and possibly add their own
    comments. If they approve, the message will be posted to their wall and to
    their friends news feeds.

Here is an example:

FacebookStory fbStory = new FacebookStory();
fbStory.setTemplateBundleId(Constants.FEED_TEMPLATE_ID);
fbStory.setPrompt("Add your thoughts if you like...");
fbStory.putData("headline", article.getHeadline());
fbStory.putData("story_url", Constants.APP_URL);
fbStory.setBodyGeneral(article.getContent());
fbStory.addImage(article.getImageURL(), Constants.APP_URL);
fbStory.showFeedDialog();

And here's the confirmation dialog displayed by this code.



That's about all there is to it. The actual Facebook API has many more features available than shown here. Over time the facebook4gwt team hopes to build more and more of these features into their implementation, so be watching for that.

8 comments:

  1. "Now add the following line to your module XML file to tell it to include the facebook4gwt module"

    which line is it??

    thanks

    ReplyDelete
  2. Thanks for catching this QicRewarder. Blogger has trouble with XML in posts sometimes. I fixed it now so you can see the line.

    ReplyDelete
  3. I've just changed the package name of facebook4gwt. It is now com.reveregroup.gwt.facebook4gwt. Make sure you have the 1.0.3 jar or later to be compatible with the <inherits> line given in this article.

    ReplyDelete
  4. It's really a nice blog. I like it. It's really informative blog. Keep it up nice blogging.
    Add, add your website in www.directory.itsolusenz.com/

    ReplyDelete
  5. I just started using the code and I am using the onLoginChanged method.. when i start the app, its seems to be getting called 3 times. Anyone else running into the same problem or know why this is happening? I am not logging in or our or anything. How can i fix this?

    Thanks

    ReplyDelete
  6. FEED_TEMPLATE_ID, how to get the FEED_TEMPLATE_ID? what is link to create facebook templates?

    ReplyDelete
  7. "Now add the following line to your module XML file to tell it to include the facebook4gwt module"

    Which module XML file is it?

    Thanks.

    ReplyDelete
  8. when i try to init Facebook, am always getting error.

    will you plz check this:

    onModuleLoad() threw an exception
    Exception while loading module com.lift.escape.client.LiftEscape. See Development Mode for details.

    java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at com.google.gwt.dev.shell.ModuleSpace.onLoad(ModuleSpace.java:406)
    at com.google.gwt.dev.shell.OophmSessionHandler.loadModule(OophmSessionHandler.java:200)
    at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:526)
    at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:364)
    at java.lang.Thread.run(Thread.java:679)
    Caused by: com.google.gwt.core.client.JavaScriptException: (TypeError) @com.reveregroup.gwt.facebook4gwt.Facebook::init(Ljava/lang/String;Ljava/lang/String;)([string: '443919819014697', string: 'http://127.0.0.1:8888/liftescape/xd_receiver.htm']): Cannot read property 'Facebook' of undefined
    at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:249)
    at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
    at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:571)
    at com.google.gwt.dev.shell.ModuleSpace.invokeNativeVoid(ModuleSpace.java:299)
    at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeVoid(JavaScriptHost.java:107)
    at com.reveregroup.gwt.facebook4gwt.Facebook.init(Facebook.java)
    at com.reveregroup.gwt.facebook4gwt.Facebook.init(Facebook.java:29)
    at com.lift.escape.client.LiftEscape.onModuleLoad(LiftEscape.java:40)
    ... 9 more

    ReplyDelete