Adding Facebook integration to an Android application

Introduction

This tutorial describes how to integrate an Android application with Facebook. We are going to authenticate using OAuth and publish a wall post on Facebook from an Android application. We will be using the Facebook Android SDK to do this.
This article is aimed at Android developers.

UPDATE Dec 04, 2011: The last couple of months there were quite some changes to the Facebook API and the Android Facebook SDK that deprecated the code in this tutorial. The “stream_publish” event was deprecated in favour of the graph API(“me/feed”) and the Facebook class from the SDK needs an app_id in its constructor now(before, it didnt and the app_id needed to be passed every time to the Facebook.authorize and Facebook.request methods). I updated the tutorial below so it is up to date again.

Context

We will implement a ShareOnFacebook activity, which will be usable standalone, and will be callable from code like:

Getting an application id from Facebook

First of all, you will need a Facebook application id. To get one, you need a facebook account first, login to that account and go to http://www.facebook.com/developers. After granting permission to the Developer app, there will be a button “Setup new application” available. After pressing this button, you will be asked for the name of your application, after which you will need to provide the application details, as in the following form:

After providing all the details, your app will be added to your (private) “current applications” on Facebook and you will be provided with an application id. Note down that application id somewhere. Note that for now the new app is not yet submitted to Facebook, which is what you want, since it is not finished yet.

The Facebook Android SDK

The facebook website API is always called through http. It will process input parameters and serve response pages/json snippets.
The Facebook Android SDK will wrap these http calls(authenticate, publish wall post,..) in an android dialog box with a webview, and enable developers to register listeners on certain events for these dialog boxes, such as unsuccesful and succesful authentication. That way, it becomes quite easy to integrate the http api in a native android application.

1. onCreate

In the onCreate method we are restoring the previously stored credentials – if any – from the SharedPreferences of the app. As we will see later, these will be set after succesful authentication.
In the onCreate method we are also setting the view to the following layout xml file:

2. share

So, if our session is not valid(if we dont have a token or the token is expired, the isSessionValid method will fail, so the user will initiate the login process again), the user will be asked to login to facebook, give the app the necessary permissions and authorize the wallpost. If the session is valid, the user will only be asked to authorize the wallpost. We will assume the user is not logged in yet. The second scenario is just a subset of the first one.

3. loginAndPostToWall

This method call will present the following dialog box on the left to the user:

after, if the user logs in succesfully, he will be asked to give permission to this app to post to his wall, as shown in the right part of the pic.

Notice how the facebook android api allows us to add custom listeners for certain events, in this case all events related to authentication.

EDIT: If the Facebook app is installed on the phone, the Facebook.FORCE_DIALOG_AUTH parameter makes sure authentication is forced. Without it, all the above will result in an endless spinning wheel, because the app keeps waiting on a login dialog but never gets it.

So, in case of failure, we will show the user a notification of the failure and finish the activity. In case of succesful authentication we are storing the credentials in the shared preferences of the application, and we are posting the message to the wall through the postToWall method.

4. postToWall

Before, the following dialog box used to be presented to the user:

But when using the new Graph API(“me/feed”), the message is directly sent through and posted to the user’s wall, without asking for confirmation.

The account owner still needs to approve the post if you are going to use the SDK, so there is no way to directly publish from code as far as I know.
The best thing is probably to use an action as in the above post, which takes care of the Facebook SDK details for you, but still goes through the login and approve pages of Facebook itself.

Is there a way to post a status on Facebook without user interaction on the last dialog? I.e. facebook.dialog(…) shows dialog on which the user should press Publish to add the status on his wall. I want to skip this part and to publish the message right after the authentication.

Hi! Thank you for the tutorial Sir! amazing!
but I’ve got some problem while making the request using your codes…
cause everytime i launch the activity, the facebook layout window just pop in a sec and then finish…
it’s seems like my facebook app interupting the sdk(i don’t know really),
cause when i remove my facebook app, your code works and I can post new message on my wall…

Thanks for your great code.
But how do you post to facebook with blue text?
and do you mean:
postOnfacebookWallIntent.putExtra("facebookMessage", "is integrating stuff again.");
at the second line of context code?

facing some issues.. however all resolved except one..shareonfacebook activity has a method call facebook.authorize(this, APP_ID, PERMISSIONS, new LoginDialogListener()); on point 3 u have discussed.
but method with these signatures is not available in Facebook.java..

It seems that an update has managed to mess up something. Was working great but now the Post Message txtbox is now blank and the text sent to it never makes it there. This started occuring somewhere between 8/1/2011 and 8/5/2011.

I am not so experienced in coding as of now. I have a task to work on. I have followed the procedure mentioned here. I am getting error in few places in my code. I just wanted to discuss these:

<> Initially I have copied the layout mentioned in this page into the my default main.xml in my project.
Line 53 : setContentView(R.layout.facebook_dialog);
I am receiving an error here as there is no such layout present. Do I pull the layout mentioned above i this page? Could some one clarify?

This code is only works for some devices with android version 2.2 but when we use Android 3.0 and some other device it doesn’t appears anything and activity automatically finished. Can any body help us about this problem?

Hi, I have this error which is
Description Resource Path Location Type
The method authorize(Activity, String[], int, Facebook.DialogListener) in the type Facebook is not applicable for the arguments (AnotherTestActivity, String[], String, AnotherTestActivity.LoginDialogListener) AnotherTestActivity.java /Integration/src/another/test line 71 Java Problem

Hi qwerty, this is because the old tutorial used an old version of the Android Facebook SDK. In the new one the APP_ID needs to be passed to the Facebook class constructor, and cant/doesnt need to be passed anymore in the authorize and request methods. Hence, there is no authorize(Activity, String[], int, Facebook.DialogListener) method anymore.

facing same problem, I want to share my pre-define text in text box(fill automatically when open share dialog ), but it’s showing blank in text box on share page. Worked on all possible way but did get success. Could any one help.

Hey Leo, yes, me and some others had the same problem. This is because the “stream_publish” event got deprecated. They seem to be still keeping it to show the dialog and everything, but you definitely cant pass it the message parameter anymore. We have to use “me/feed” now.

Hi,
I Still cant get the application to run.After i click on “share on facebook” only thing that happens is i can see the spinner and then application returns back to the dialog box asking if i want to share again.please help.

Hello,
I registered my app on facebook, used your code, and put the app on my phone. When I click submit a dialog box with a spinner displays then it quits back to the “do you want to share this on facebook” screen. No toast message appears and nothing gets posted to my facebook. When I put this on the emulator and ran it, it worked fine and posted to facebook. Any idea why this is happening?

It seems that having the Facebook app from android Market installed on device/emulator creates the problem that David and Ranjeet experienced.
Having the Facebook app installed I get the dialog over and over again and the application does not post anything on my wall
Uninstalling the Facebook applications solved the problem
Is there any solution that ShareOnFacebook to work with Facebook application installed? I’m asking this because there are lots of users that have the application installed

but the problem with this code is the EXTRA_TEXT has to contain an url. Plain text does not work. In an app of my own I used this method, but I ended up appending a link to the app’s homepage to every message.

Hi I Found a solution for your problem see here
public void loginAndPostToWall() {
facebook.authorize(PostwallActivity.this, PERMISSIONS,new LoginDialogListener());
}
previously tour using this for login replace this line to

public void loginAndPostToWall() {
facebook.authorize(PostwallActivity.this, PERMISSIONS,Facebook.FORCE_DIALOG_AUTH,new LoginDialogListener());
}
you got a optput and get your app login page only but not a main facebook app login page. i Think it is use full for u.

Hi,
Thank you very much as I really wanted this tut…
I ran the code as you are given and its runs smoothly… Thank you again
But I just have on problem, I want the publish dialogue box to be seen as I want user to edit the message on go.. how do I do that… as I am not able to see the publish dialogue box…

Hi,
your application works perfectly on android emulator but when i try to setup it on my device, the facebook login page say “cookies are not enable.” it also all cookies are enable.
What do you think ??????????????? ?

this code is working if the official facebook app is not installed on the phone.
This code does not use the SSO solution of facebook. I dont get it running by my own. Can someone provide an explanation how it should work with sso and facebook app installed.

Hello, you need to replace the line
facebook.authorize(this, PERMISSIONS, new LoginDialogListener());
with
facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
to make it work when the Facebook app is installed.

Hi.. Thanks for this post. It has helped me a lot. I am having a small problem though. I was developing an app and I used your code to successfully implement “post on facebook” feature. I had tested it many times on an actual device and it was always successful. Now the app is published. I tried downloading the app and then tried using this feature. Unfortunately, it does not work. I am using Eclipse. Do we need to make any changes in the code before publishing the app like using a different key etc..? I fail to understand what went wrong the moment I published the app. Please help.

Dude, your guide is, BYFAR, the best one avaiable on the internet, spend 3 days working on this without sucess until I found your code, really easy and clean. One question, I dont want to imediatly post on the wall, I want teh user to be able to edit the text before and then click on “publish” to post, how can I do that? Thanks again

Hi Steffen, first of all thanks for your post, it really help me out.
So after lots of problems I finally can run the program, but now i don’t know where do I have to make the call (That context part tree-line-code) cause my program is mostly about xml pages, so I can’t use the java script.
Should i make a java file with just that code and then make a call from the xml file to open that java file? How can I make that?
I really appreciate your help, thanks for all.

I would like to ask some problem
I input my facebook account after I run it.
But It is not necessary to input my account when I use it again.
How can I input the facebook account again because I want to allow the user to post their message on different facebook if the user has at least one facebook account.(Now I am using the eclipse to run,but I cannot input the different facebook account when I run the code again and It will post the message on my the first facebook account directly.

You have a bug here. If the user doesn’t have facebook installed or has it installed but isn’t logged in then when they return to the activity (after fb prompts to download the app) they will see a blank dialog. How can this dialog be closed?

Nice post,
anyway using sdk higher than 11 an exception will be thrown.
Replace postToWall() method with these lines to be compatible with HoneyComb
or a NetworkOnMainThreadException will be raised
I use an extension of AsyncTask to post the message

please help out when i am trying on android 2.2,it is working fine but when i tested it on api 16 it is not working,one more problem is that once a user logins into one account and the message is posted on the wall,now there is no option to logout from fb account again if user want to post from some other account it is not coming

Thanks for the wonderful tutorial. I got everything working.
But I have one questions here. After the successful login, if the user goes to web and revokes the access for this app, How do we handle it in Andorid code? I tried to see if there will be any error (i mean it returns false) in facebook.isSessionValid() but it still returns true but the posting fails. How can we handle this???

I had to do a minor adjustment that I want to share with others: on the postToWall, if the user revokes access to the app on FB, the Android App, as it is, never realizes it. So, I had to add this to the method: