One of the common features on current mobile application is the ability to share content on social media websites such as Facebook, Twitter and Foursquare. Most of the large social media provide API to enable developers to integrate third party application with their service. Facebook as the largest social media has a very well designed API and available to many programming languages.
Facebook has an official SDK for Android platform that can be used easily by developers to integrate their application. In this tutorial, i’ll explain how to use Facebook SDK for Android to post status to Facebook wall from an Android application. I have written similar tutorial for Twitter to show how to post status to Twitter from Android and for Foursquare to show how to connect and use Foursquare API on Android.
I. Register Facebook Application
To enable user to post status to Facebook, first you have to create a Facebook application:
- Login to Facebook and go to Facebook Developer page then register your application by clicking the Create New App button on top right of the page.
- Fill the App Name with your application name.
- Note the App ID, we will use it later on Android code. Note that you don’t have to select how app integrate with Facebook option, just click the Save Changes button.
II. Android Integration
To integrate Facebook with Android, you can use official Facebook SDK for Android that can be downloaded from github page. For sample project in this tutorial, i use old version of Facebook SDK downloaded from the github page with some small modification. If you want to use the latest version, just download the SDK from the link above.
In my sample project, i create two packages, one for Facebook SDK and the other for application main package.
Code implementation
1. Facebook Connection (TestConnect.java)
This example shows how to connect to Facebook, display webview dialog to authorize user then save the access token and username on shared preference for later use.
public class TestConnect extends Activity { private Facebook mFacebook; private CheckBox mFacebookBtn; private ProgressDialog mProgress; private static final String[] PERMISSIONS = new String[] {"publish_stream", "read_stream", "offline_access"}; private static final String APP_ID = "*****app id ******"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mFacebookBtn = (CheckBox) findViewById(R.id.cb_facebook); mProgress = new ProgressDialog(this); mFacebook = new Facebook(APP_ID); SessionStore.restore(mFacebook, this); if (mFacebook.isSessionValid()) { mFacebookBtn.setChecked(true); String name = SessionStore.getName(this); name = (name.equals("")) ? "Unknown" : name; mFacebookBtn.setText(" Facebook (" + name + ")"); mFacebookBtn.setTextColor(Color.WHITE); } mFacebookBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onFacebookClick(); } }); ((Button) findViewById(R.id.button1)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(TestConnect.this, TestPost.class)); } }); } private void onFacebookClick() { if (mFacebook.isSessionValid()) { final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Delete current Facebook connection?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { fbLogout(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); mFacebookBtn.setChecked(true); } }); final AlertDialog alert = builder.create(); alert.show(); } else { mFacebookBtn.setChecked(false); mFacebook.authorize(this, PERMISSIONS, -1, new FbLoginDialogListener()); } } private final class FbLoginDialogListener implements DialogListener { public void onComplete(Bundle values) { SessionStore.save(mFacebook, TestConnect.this); mFacebookBtn.setText(" Facebook (No Name)"); mFacebookBtn.setChecked(true); mFacebookBtn.setTextColor(Color.WHITE); getFbName(); } public void onFacebookError(FacebookError error) { Toast.makeText(TestConnect.this, "Facebook connection failed", Toast.LENGTH_SHORT).show(); mFacebookBtn.setChecked(false); } public void onError(DialogError error) { Toast.makeText(TestConnect.this, "Facebook connection failed", Toast.LENGTH_SHORT).show(); mFacebookBtn.setChecked(false); } public void onCancel() { mFacebookBtn.setChecked(false); } } private void getFbName() { mProgress.setMessage("Finalizing ..."); mProgress.show(); new Thread() { @Override public void run() { String name = ""; int what = 1; try { String me = mFacebook.request("me"); JSONObject jsonObj = (JSONObject) new JSONTokener(me).nextValue(); name = jsonObj.getString("name"); what = 0; } catch (Exception ex) { ex.printStackTrace(); } mFbHandler.sendMessage(mFbHandler.obtainMessage(what, name)); } }.start(); } private void fbLogout() { mProgress.setMessage("Disconnecting from Facebook"); mProgress.show(); new Thread() { @Override public void run() { SessionStore.clear(TestConnect.this); int what = 1; try { mFacebook.logout(TestConnect.this); what = 0; } catch (Exception ex) { ex.printStackTrace(); } mHandler.sendMessage(mHandler.obtainMessage(what)); } }.start(); } private Handler mFbHandler = new Handler() { @Override public void handleMessage(Message msg) { mProgress.dismiss(); if (msg.what == 0) { String username = (String) msg.obj; username = (username.equals("")) ? "No Name" : username; SessionStore.saveName(username, TestConnect.this); mFacebookBtn.setText(" Facebook (" + username + ")"); Toast.makeText(TestConnect.this, "Connected to Facebook as " + username, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(TestConnect.this, "Connected to Facebook", Toast.LENGTH_SHORT).show(); } } }; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { mProgress.dismiss(); if (msg.what == 1) { Toast.makeText(TestConnect.this, "Facebook logout failed", Toast.LENGTH_SHORT).show(); } else { mFacebookBtn.setChecked(false); mFacebookBtn.setText(" Facebook (Not connected)"); mFacebookBtn.setTextColor(Color.GRAY); Toast.makeText(TestConnect.this, "Disconnected from Facebook", Toast.LENGTH_SHORT).show(); } } }; }
[ad]
line 6: Define the Facebook permission list, publish_stream, read_stream, and offline_access is enough to enable Android app to write status on Facebook wall. If you want more permissions, just add them into the PERMISSIONS array.
line 8: Set the Facebook application id, use the App ID from Facebook application settings page as described above.
line 19: Instantiate the Facebook class with APP_ID as the parameter. Facebook class is the main class for interacting with Facebook API endpoint.
line 23: Check if user has been authenticated before. Method isSessionValid is used to check if there is already access token saved on preference file. If user has been successfully authenticated, the access token and the name of authenticated user will be saved on preference file. The name of preference file is defined within SessionStore class on KEY variable. You can change the name of preference file as you want.
line 33+48: Check if user has been authenticated, if yes, display the confirmation dialog to log out from current session (also delete the access token from preference file). If not, display the authentication dialog (webview dialog).
line 77: Define the listener for authentication dialog and override the four methods to handle four different events: onComplete: is called when user successfully authenticated, here we save the access token to preference file (line 79), onFacebookError: is called when there is an error while authenticating user, onError: is called when there is an error on dialog and the last is onCancel: is called when user cancel the dialog.
2. Post Status (TestPost.java)
This example shows how to post status to Facebook wall.
public class TestPost extends Activity{ private Facebook mFacebook; private CheckBox mFacebookCb; private ProgressDialog mProgress; private Handler mRunOnUi = new Handler(); private static final String APP_ID = "*** put app id here"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.post); final EditText reviewEdit = (EditText) findViewById(R.id.revieew); mFacebookCb = (CheckBox) findViewById(R.id.cb_facebook); mProgress = new ProgressDialog(this); mFacebook = new Facebook(APP_ID); SessionStore.restore(mFacebook, this); if (mFacebook.isSessionValid()) { mFacebookCb.setChecked(true); String name = SessionStore.getName(this); name = (name.equals("")) ? "Unknown" : name; mFacebookCb.setText(" Facebook (" + name + ")"); } ((Button) findViewById(R.id.button1)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String review = reviewEdit.getText().toString(); if (review.equals("")) return; if (mFacebookCb.isChecked()) postToFacebook(review); } }); } private void postToFacebook(String review) { mProgress.setMessage("Posting ..."); mProgress.show(); AsyncFacebookRunner mAsyncFbRunner = new AsyncFacebookRunner(mFacebook); Bundle params = new Bundle(); params.putString("message", review); params.putString("name", "Dexter"); params.putString("caption", "londatiga.net"); params.putString("link", "http://www.londatiga.net"); params.putString("description", "Dexter, seven years old dachshund who loves to catch cats, eat carrot and krupuk"); params.putString("picture", "http://twitpic.com/show/thumb/6hqd44"); mAsyncFbRunner.request("me/feed", params, "POST", new WallPostListener()); } private final class WallPostListener extends BaseRequestListener { public void onComplete(final String response) { mRunOnUi.post(new Runnable() { @Override public void run() { mProgress.cancel(); Toast.makeText(TestPost.this, "Posted to Facebook", Toast.LENGTH_SHORT).show(); } }); } } }
line 46: Instantiate the Facebook asynchronous thread that will be used to send status to Facebook.
line 52: Use Bundle as data wrapper to send data
line 54: message, is the Facebook status message
line 55: name, is the link title
line 56: caption, is the caption text below the link
line 57: link, is the link to go when user clicks on the title
line 58: description, is the desciption text below the caption
line 59: picture, is the image link. The image will be displayed on the left of description
line 61: post the status to facebook. me/feed parameter means the status will be posted on current authenticated user’s wall. WallPostListener is the listener to be called when the asynchronous thread finished sending the post to Facebook.

You can download the source code on my github page







Saved lot of work for me I guess. Thank you for sharing this.
Initial testing went well. I hope that integrating it into my application will be easy too 🙂 Also have to check out your similar posts about twitter and foursquare too.
Hi Janar, thanx for the feedback, hope the others will work well too 😉
You are officially my android guide man 🙂
This helps me really so much after a lot of searching. Thanks
You’re welcome …;)
I dowloaded this code and run with my facebook app id its displaying “Posted to Facebook” toast message but its not post in my Facebook wall-post please help me
Thanqu
Dear lorenz,
there is relogin problem with this app it gives user name unknown after deleting facebook connection & logingin with same uname & password..
please help me…. 🙁
click below link & download app please identify problem after login,disconnecting & relogin. it is not posting on wall again. only it posts for first time. please help me.
https://market.android.com/publish/Home?pli=1#ViewStatisticPlace:p=com.irobotz.quote
Hi Punit,
Could you just give me the apk file so i can test it on emulator? Thnx
Hey lorenz u can find apk file from below link thank u for rply & please give me solution if possible as early as possible 🙂
https://market.android.com/details?id=com.irobotz.quote&feature=search_result
Hi Punit, i’ll check it, i’ll give you the update on next comment. Be patient..;)
Hi lorenz,
thanx, i tried lot but… 🙁 i think there is problem of msg.what’s value at the time of logout or session clear problem. goood if u can help me. waiting…. for rply 😀
Hi Punit, i didn’t find how to logout fb from your app. Could just give me the logcat message ?
Hi lorenz,
i sent ya d logcat msg but after dat dis page was not accessible for me.. so i made temporary changes to date n disable logout & now it is possible to share widout relogin…
thanx
check out my app @
https://market.android.com/details?id=com.irobotz.quote
Ya but one new issuse is der for twitter wat to do wid pin , dey r giving after authorizing app ?
i am making new app in which i want search users on twitter but facing problem…
please find correction in link
https://market.android.com/details?id=com.irobotz.quote&feature=search_result
hei, it was running well, but i want asking some question.
in firs project it can be logged in with no name.
why it can be happen?
when we login as no name? are we really log with our account.
sorry for my bad english.
thx a lot for sharing 🙂
Hi , i never tried that (logging in with no name), but that might be a bug..i’ll try to investigate that…… You’re welcome..;)
Hey Lorenz,
in my Quotes Board app i have removed Delete Current fb connection option & updated. so others can’t log in from der device without clearing app data.
i have posted logcat of your given source project. in which logout is successfull but when i am relogin it shows facebook(No Name). so u can also refer your uploaded source project after login once & logout & then relogin after deleting current connection in TestConnect Facebook(No Name) & TestPost Facebook(Unknown) ….
Hi Lorenz,
You mention that this example uses the old version of Facebook SDK downloaded from the github page with some small modification.
Have created a version which utilizes the *current* Facebook SDK?
Hi lorenz,
Thank you for this amazing tutorial but I have some problems. When I test the sample code it run well but language in facebook login page is not English (US) how can I set default language to English (US)?
Hey Lorenz,
Thanks dude its a nice post. Help me a lot.I will wait for your next post…..
Thanks once again
Thanks & you’re welcome..;)
thxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
thxxxxxxxxxxxxxxxxxxxx alot
Your comment is awaiting moderation.
dis status if for my prev comment logcat msg
“I am getting old :(”
lolz, just kidding. I’ve found your blog today, and your tuts really helped me a lot.
Thank you.
dx
Thanks for this 😉
Thank you for posting this, i guess it’s gonnna help me a lot in my application. One questions though, where the hell do you find all the information about facebook SDK? like what methods to use to do certain things.
I’ve been longing to find something as useful as this.
Again, thank you.
Hi Lorenz Thank you very much for the post One questions though,
I am able to post some text on fb wall with image using ‘picture’ attribute. I observed that every time, the image is saved in the Album. I want to stop this.
I want to post some text with image but i don’t want that particular image to be saved in the album
If you still didn’t get my question please go through the my answer here http://stackoverflow.com/questions/8662460/android-app-how-to-upload-photo-from-sdcard-to-facebook-wall/9884139#9884139 My username is KK_07K11A0585
Hi Krishna, i think it is impossible to upload a photo to facebook without saving it to album. The possible way is to use external image storage and then post the link to that image on facebook wall.
Hi lorenz, thank u for your quick reply!!!
I am saving the image in album and i was able to get the url of the image which is saved in the album and i am trying to post the same image using its url. But i was gettting
Oauthexception (#100) fbcdn image is not allowed in stream 🙁 🙁
I have searched about this exception and came to know that we cannot upload images which are already there in album.
If it is so can you suggest me a way such that i can post an image that is existing in my device to fb wall. I dont care whether it is saved in album or not but i want that image to be appeared along with my post …..
It would be really helpful to me if you come with a solution. The problem is that every time we may not get the image url … We have to some images from local like from gallery or from camera …
You told me that it is possible by an external image storage. But, can we store images into it programatically ??? 🙁
would u plz share how to post pic on facebook …
i wanted to post pic on facebook using camera…
thanks in advance ….
Hi lorenz,
thanks a lot for this tutorial really amazing and saved my life
I just wanted to ask one thing, when you start logging in the page is in indonesian not english
any idea how the log in page starts with english and don’t have to change it from inside the log in page?
thanks in advance man
thanks a lot…i searched a lot to post images with other content but your post is really helpful.
thanks again. 🙂
Hi Lorenz. First of all congratulations for the tutorials, I find them very very very very VERY useful. But I encountered a problem: in the TestPost page, Eclipse keeps saying that there is an error on SessionStore (“SessionStore cannot be resolved”).
I’m using the package com.facebook.android (the one with asyncfacebookrunner, dialogerror, facebook, facebookerror, fbdialog and util). As far as I tested the login goes well (it’s not the same code as you posted here, I made it myself)… do you have any suggestion?
Having same problem….. Please help us Lorenz
Hi
Excellent stuff. Do you mind if I reuse some parts of your code in my pet project ?
Regards
Pranam
itzz working
great work
keep gooing…
hey when i paste the TestConnect.java in
my source file im getting error like
checkbox cannot be resolved to a type,dialog box cannot be resolve to a type.do i need to import any header files to run it with errors
Hi lorenz,
I m using dis app project regularly to post on fb quickly but I am facing one problem that sometime I am posting on fb itvis showing posted to fb but its not showingvon my wall & aftrer disconnecting from fb & rrconnecting problem fixed I can post… But again after some time or days same problem… I need to relogin again and again please fix as early as possible.
Hi Lorenz,
I have followed your example and i also implemented a customized too,
my Query is when i post any status it shows “via Android SDK Simple Sample App”
can we change to any other title or personal App name…
For some reason the code is giving error in two things.
1. SessionStore cannot be resolved as type.
2. ((Button) findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {
and this line is giving error that button cannot be resolved as type and OnClickListener cannot be resolved as type. PLEASE HELP!!!!
SessionStore.java and BaseRequestListener.java are missing!!!!! kindly help!!!! ITs not there in the download link
Can you give the content of the SessionStore.java file?
Just what i needed. 🙂
I haven’t tries it yet but after updating the status how will you log out?
Does it logs out on its own after posting?
Hey man thanks a ton… I really dint know what was next after downloading the Facebook sdk… This post actually explained wat i’m supposed to ….
thanks a ton. cheers…!! \m/
Hi,
this post was awesome and it helps me a lot. Is there any way to upload video from sdcard to facebook
have been getting error, while running testpost.java …
It shows the error in ,
error :mAsyncFbRunner.request(“me/feed”, params, “POST”, new WallPostListener());
error : private final class WallPostListener extends BaseRequestListener
for this logcat message is
Description Resource Path Location Type
The type TestPostFacebook.WallPostListener must implement the inherited abstract method AsyncFacebookRunner.RequestListener.onFacebookError(FacebookError, Object) TestPostFacebook.java /Oneupload/src/com/oneupload/Gprakash line 93 Java Problem
The type TestPostFacebook.WallPostListener must implement the inherited abstract method AsyncFacebookRunner.RequestListener.onFileNotFoundException(FileNotFoundException, Object) TestPostFacebook.java /Oneupload/src/com/oneupload/Gprakash line 93 Java Problem
The type TestPostFacebook.WallPostListener must implement the inherited abstract method AsyncFacebookRunner.RequestListener.onMalformedURLException(MalformedURLException, Object) TestPostFacebook.java /Oneupload/src/com/oneupload/Gprakash line 93 Java Problem
The type TestPostFacebook.WallPostListener must implement the inherited abstract method AsyncFacebookRunner.RequestListener.onIOException(IOException, Object) TestPostFacebook.java /Oneupload/src/com/oneupload/Gprakash line 93 Java Problem
The type TestPostFacebook.WallPostListener must implement the inherited abstract method AsyncFacebookRunner.RequestListener.onComplete(String, Object) TestPostFacebook.java /Oneupload/src/com/oneupload/Gprakash line 93 Java Problem
The method request(String, Bundle, AsyncFacebookRunner.RequestListener, Object) in the type AsyncFacebookRunner is not applicable for the arguments (String, Bundle, String, TestPostFacebook.WallPostListener) TestPostFacebook.java /Oneupload/src/com/oneupload/Gprakash line 90 Java Problem
Hi i used your sample code it worked fine i get the news feed using mFaceboof.request(“me/home”);
now i want to like or comment what should i use i am blank please help.
O thanks man help me alot.
Saved my time.
Stay Blessed
Hi lorenz,
Thnx a lot. this was amzng…..
i want to post an image on facebook using camera or sd card, can u help me……
thank you very much
it works.
This is all I need
^.^
Thanks for sharing. It helps me a lot, since it’s very hard to find a good documentation on the internet~
This is awesome! thanks dude!..
When I tried to post a status, I can’t see it?
Thank You in advance
How to post a status on friends wall or any way to TAG them in comment status ?
Hi lorenz,
Thnx a lot. It helps me a lot…
i want to post an image on facebook using camera or sd card, can u help me……
now facebook sdk 3.0 is available missing session methods ..please provide help to integrate this sdk for posting
Awesome post. Made FB integration very simple and straightforward. Thank you!!
Hi lorenz sir,
I am getting error on relogin,when i use my facebook app keyn then it runs ok,but when others tries to login then it gives error on webDialog,sorry for bad english,pls help..
this tutorial is nice to catch up, keep posting dude :d
Hi ! test worked perfectly fine ! Great work keep it up ! Much appreciated
Brother…
plese help me…when im paste ur code to my project the SessionStore class is not there…even in my facebook SDK didnt have it…i searched it everywhere and found the sorce code for that class..so i manually implement it..but this methode [sessionstore.getName] is not even there….im stuck with my implementations…please help me…what is the errer…and plese can u mail me the whole project for me…im doing this for my school project…plss plsss….i beg u….
I am getting an error “SessionStore cannot be resolved”. Can you please provide this file.
hi Lorenz , gud work ,,
do u know how to post comments on facebook pages .. (Not in users wall )
“http://www.facebook.com/Vaisaktrialpage”
This is a facebook page , i want to post comments in this page from android device …
” Utility.fb.dialog(MainActivity.this, “id=527120300657925/feed”,params,new DialogListener()”
i tried this code but its showing error that “The page u requested was not found”..
Hi,
Working good.. Thanks bro..
Where is SessionStore object???? Please explain… thanks
I’m following these tutorial
http://sunil-android.blogspot.com/2013/08/facebook-integration-with-android-app.html
But i dont know how to post on wall so it can be shown just like what you did.
I already tried it but unfortunately it give me error.
11-29 11:35:36.720: E/AndroidRuntime(14567): Process: co.id.catalyst.ayuberhemat, PID: 14567
11-29 11:35:36.720: E/AndroidRuntime(14567): java.lang.NullPointerException
11-29 11:35:36.720: E/AndroidRuntime(14567): at co.id.catalyst.activity.ItemsDetailActivity.postToWall(ItemsDetailActivity.java:450)
11-29 11:35:36.720: E/AndroidRuntime(14567): at co.id.catalyst.activity.ItemsDetailActivity$1.onClick(ItemsDetailActivity.java:176)
Can you help me to this
Thank you
How to post my status as public. As this post is only showing in my wall.
Please help me…please
How to post as public as this post is only showing in my wall.
Please help me…please
Hey bro!!! Thank you very much …..I was scratching ma head on this from a very long time………But this helped me a lot……U rocckkkkkkkkkkk:))
SessionStore cannot be resolved plz any help?
Very Helpful, Thanks…
Can we tag our friends in status? Kindly help
Did u use version 3.14.1 for this integration ?? Please reply coz i am in dire need to use this sdk for my app.
The user hasn’t authorized the application to perform this action”,”type”:”OAuthException”,”code”:200}}
plz help me plzzzzzzzz
I have post through application but post not display on Facebook wall any one help me.
how to upload camera capture images on facebook…
I was struggling while using ANDROID FACEBOOK SDK when app is not installed on device. I have only one button on which I have to login as well as share the post. For the same with some modification in your code works like charms. Thanks.
I am new in this market and i am asking can i use the posting message code without using the connecting code ?
Hey, first of all I would like to say what I great job you did here. It helped me a lot. Thanks.
I have only one question. I integrated your code to my application and it works fine. No error, no problem with login, logout, nothing, I post and comes all messages, posting and “Posted to facebook”, but it does not post. I don’t see any post on facebook and that is my problem, because there is no error, I have no idea where to look. Have you seen this problem before? Can you help me?
Thanks in advance.
Best regards.
And congrats again, great job.
Im chaging the APP_ID and it works fine and im connected to facebook and the apps. but the post button is not working nothing appears when i post something., nothing appear in my profile. HELP ME,
message is not posting on the fb wall but im getting the toast message as “posted to facebook”
Hi,
Post is not working for me, exception is java.io.FileNotFoundException: https://graph.facebook.com/me/feed
Can you please tell me why it is happen.
Thanks.
Hi,
Post feed is not working for me , exception ( java.io.FileNotFoundException: https://graph.facebook.com/me/feed ) occurred can you please tell me why it is happen.
Thanks.
Let’s say I wanted to put a byte array as params. Is that possible? Because I do not have the URL for my picture
This example not working for me Sir.but output coming as “Posted to Facebook”