How to Use Facebook SDK to Post Status From Android

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.
    Create New Facebook App
  • Fill the App Name with your application name.
    Facebook Create New App
  • 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.
    Facebook App Setting

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.

Facebook Android SDK

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();
			}
		}
	};
}

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.

facebook sdk android facebook sdk android

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.

facebook post status android

facebook wall android

Facebook Wall

You can download  the source code on my github page

facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

Comments

  1. says

    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.

  2. says

    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…. :(

  3. says

    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 :)

  4. says

    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) ….

  5. Art Jervis says

    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?

  6. besureita says

    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)?

  7. dx says

    “I am getting old :(”

    lolz, just kidding. I’ve found your blog today, and your tuts really helped me a lot.

    Thank you.
    dx

  8. Mike says

    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.

  9. krishna kanth says

    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

    • says

      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.

      • krishna kanth says

        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 ??? :(

  10. NITIN @ says

    would u plz share how to post pic on facebook …
    i wanted to post pic on facebook using camera…
    thanks in advance ….

  11. Ali says

    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

  12. ramesh says

    thanks a lot…i searched a lot to post images with other content but your post is really helpful.
    thanks again. :)

  13. Leon Guerrero says

    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?

  14. Pranam says

    Hi

    Excellent stuff. Do you mind if I reuse some parts of your code in my pet project ?

    Regards
    Pranam

  15. jeyaram says

    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

  16. Shah says

    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.

  17. Patric says

    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…

  18. Kshitij says

    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!!!!

    • Kshitij says

      SessionStore.java and BaseRequestListener.java are missing!!!!! kindly help!!!! ITs not there in the download link

  19. Anonymous says

    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?

  20. Vivekanand says

    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/

  21. karthik says

    Hi,
    this post was awesome and it helps me a lot. Is there any way to upload video from sdcard to facebook

  22. prakash says

    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

  23. Shahid Farooq says

    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.

  24. minu says

    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……

  25. Jhansi says

    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……

  26. cristeen says

    now facebook sdk 3.0 is available missing session methods ..please provide help to integrate this sdk for posting

  27. kalu khan says

    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..

  28. Darshana says

    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….

  29. Rahul Kumar Goel says

    I am getting an error “SessionStore cannot be resolved”. Can you please provide this file.

  30. vaisak says

    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”..

  31. chris says

    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

  32. chetan says

    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:))

Leave a Reply

Your email address will not be published. Required fields are marked *