Home > Facebook SDK > A 30 minute guide to integrating Facebook in your Android application

A 30 minute guide to integrating Facebook in your Android application

Introduction

The goal of this article is to get Facebook integration up & running from your Android app in 30 minutes. The guide will show you how to

  • setup a Faceook test account
  • register a Facebook application
  • authenticate the user in your Android application.
  • have the user update his Facebook wall from your Android application.

This guide is accompanied  by a sample application that’s available in Github in the AndroidFacebookSample repository. To import this project in Eclipse, I suggest using the EGit plugin that can be installed via the Main P2 Repository located at http://download.eclipse.org/egit/updates.

Before running this project, make sure you change the com.ecs.android.facebook.Sample.AndroidFacebookSample file to include your Facebook API key (see subsequent section).
Once you have sample application up & running, you can copy the relevant classes into your projects to have Facebook up & running from your Android application.

First things first … In order to integrate with Facebook, you need 2 things :

  • A Facebook test account, used in our Android application to login to Facebook and make status updates.
  • A Facebook application, used to inform the user in your Android application that this application is requesting you to login to Facebook.

Facebook Test Account

We’ll start by creating a test account that we’ll use in our Android application. Signup for a new user account at Facebook. If you already have an account, sign up for a new account using your existing name but specify a different email address. Once the account has been created, we’ll convert it into a Facebook test account.

Note : The following step should not be done on your real facebook account. Converting an existing Facebook account into a test account is irreversible, so please ensure that you do the following step with your newly created “dummy” account.

When logged into Facebook, goto the Facebook Become Test Account page  to convert your newly created account into a Facebook test account. Again, do not execute these steps on your “real” user account.

After confirming that you want to convert your account into a test account, you should see the following message :

Facebook Application

Next step is to create a Facebook application. Integration with facebook is based on OAuth 2.0 and requires your to register a Facebook application. Visit the Facebook Developers Authentication page for more information on its OAuth 2.0 implementation.

The Facebook application that we’ll create will have it’s own Application ID that we’ll use in our Android application.

Creating an application cannot be done on the Facebook test account, so you’ll need to have a proper Facebook account in order to create the application. Using your “real” Facebook account, goto the Facebook Create Application page  and create your application.

Give it a name, and complete the registration. You should land on a page like this :


So far so good, everything is setup on the Facebook front, now it’s time to start coding our Android application.

On the Android front, we’ll use the Facebook Android SDK located at Github : https://github.com/facebook/facebook-android-sdk
The Facebook Android SDK is licensed under the Apache License and is completely open source.

The project contains several samples in the examples folder, but the core SDK is located in the facebook folder. The sample application included in the facebook sdk repository provides the user the ability to post a message on the wall using a custom dialog, allowing the user to enter some text. The goal of the sample application that we’ll be creating here is to send an automated message to the wall, without any human interaction. Our application will generate a piece of text and post it on the wall without showing a dialog to the user. The user simply presses a button, and the generated message will appear on his/her wall.

But to get started, we’ll begin by importing the facebook project (containing the actual facebook sdk) into Eclipse. Once this is done, you should have the following Eclipse Project in your workspace :

As this is the library project that our sample application will use to do the actual  Facebook integration, we’ll  need to create a reference in our own project to this Facebook Android SDK project. This is done by going to our project properties, select Android on the left, go to the library section and click Add.

On the following screen, you can select the Facebook Android SDK library project

When selected, it will be made available to your own project.

As you can see in the Eclipse Package explorer, our sample project now also contains a reference to the Facebook Android SDK project

The Facebook SDK project revolves around a central com.facebook.android.Facebook.Facebook class, allowing you to perform various calls to Facebook.  It provides basic login/logoff functionality (by leveraging single sign on capabilities if you have the official facebook app installed), handles the OAuth integration, and provides you with a generic API to perform requests to the various Facebook APIs.

In our own sample application, we’ll encapsulate all the Facebook interactions in a FacebookConnector object. The object is constructed like this

	public FacebookConnector(String appId,Activity activity,Context context,String[] permissions) {
		this.facebook = new Facebook(appId);

		SessionStore.restore(facebook, context);
        SessionEvents.addAuthListener(mSessionListener);
        SessionEvents.addLogoutListener(mSessionListener);

		this.context=context;
		this.permissions=permissions;
		this.mHandler = new Handler();
		this.activity=activity;
	}

As you can, under the hook, our FacebookConnector class uses the Facebook class provided by the Facebook SDK project.

Our FacebookConnector will provide a more coarse-grained API than the Facebook class. The Facebook class is designed in a very generic way, allowing you to do a lot of different calls to Facebook. This design results in a fairly fine-grained API, where some knowledge is expected from the application using this API. For example, you’ll need to know the specific endpoints for post a message on a wall, or to retrieve a user profile. In addition to that, you’ll also need to know what parameters you need to send for each request.

Our FacebookConnector exposes a coarse-grained method called postMessageOnWall that’s the main logic behind our Post button. The only thing we need to provide is the actual message we want to post. The FacebookConnector will do the necessary plumbing towards the more generic Facebook class.

The postMessageOnWall method checks if we have a valid Facebook session (meaning we have authenticated properly against Facebook). If this is the case, it setups up the necessary parameters, and does a call through the Facebook class to post a message on the wall. (using the me/feed endpoint)

	public void postMessageOnWall(String msg) {
		if (facebook.isSessionValid()) {
		    Bundle parameters = new Bundle();
		    parameters.putString("message", msg);
		    try {
				String response = facebook.request("me/feed", parameters,"POST");
				System.out.println(response);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			login();
		}
	}

But we’ll start by explaining what happens if the user doesn’t have a valid Facebook session.

If the user hasn’t authenticated to Facebook yet we need to perform a login. The login() is defined like this :

	public void login() {
        if (!facebook.isSessionValid()) {
            facebook.authorize(this.activity, this.permissions,Facebook.FORCE_DIALOG_AUTH,new LoginDialogListener());
        }
    }

The login method is implemented in such a way that when we don’t have a logged in user, we call the facebook.authorize to start the Facebook OAuth flow. Although the Facebook SDK has a single-sign-on option, allowing you to leverage your existing facebook session you may have with the official Facebook Android application, we’ll add the Facebook.FORCE_DIALOG_AUTH parameter to have the Facebook SDK pop the login dialog.

The first thing that will happen when executing this method, is that the Facebook login dialog will be shown. Notice how the login dialog mentions the Facebook app we created earlier. By passing on our Application ID to the Facebook object, the user is now informed that the TestAndroidIntegration application is initiating the Facebook login. The user can decide at this point if he wants to login to his Facebook account.

When the user does a login, he’ll be presented with yet another dialog. Keep in mind that at this point, although the user is logged in, he didn’t give any permissions yet for this application to post messages on his wall. This particular dialog will now request the user for certain permission.

It basically allows the user to authorize the TestAndroidIntegration application to access basic information and Post to my Wall.  Accessing basic information is the default permission that is given when a user logs in this way. Here, an additional permission is requested (Post to my Wall).

In order to post something on the wall, the publish_stream permission is required, hence we pass this on to our FacebookConnector :


	private static final String FACEBOOK_APPID = "PUT YOUR FACEBOOK APPID HERE";
	private static final String FACEBOOK_PERMISSION = "publish_stream";

	facebookConnector = new FacebookConnector(FACEBOOK_APPID, this, getApplicationContext(), new String[] {FACEBOOK_PERMISSION});

Note : ensure that you provide a proper Facebook APPID here.

When the user allows this request for permission (authorization), the Facebook API can begin executing requests on behalf of the user (like posting something on his wall).

Posting a message on the Facebook wall

In order to post a message on the wall, we basically construct a message (Bundle) that we pass on to the facebook request method. We use the “me/feed” ID on the Facebook Graph API to indicate that we’ll be posting something to the Profile feed (Wall in Facebook terminlogy).


	private FacebookConnector facebookConnector;

	private void postMessageInThread() {
		Thread t = new Thread() {
			public void run() {

		    	try {
		    		facebookConnector.postMessageOnWall(getFacebookMsg());
					mFacebookHandler.post(mUpdateFacebookNotification);
				} catch (Exception ex) {
					Log.e(TAG, "Error sending msg",ex);
				}
		    }
		};
		t.start();
	}

The postMethodOnWall() method is called from our main Activity in a background thread. Although we don’t want to interrupt the main UI thread while posting the message (hence the background thread), we do want to send a notification to the user that his message was posted. We use a handler for this in order to show a Toast message on the main UI thread once the background processing has been done.


	private FacebookConnector facebookConnector;

    final Runnable mUpdateFacebookNotification = new Runnable() {
        public void run() {
        	Toast.makeText(getBaseContext(), "Facebook updated !", Toast.LENGTH_LONG).show();
        }
    };

An importing thing to note is that when the user clicks the Post Message button, besides logging just logging in, we also want to send the message to the Facebook wall. Performing the login, immediately followed by an action (in this case sending a message) can be done by adding a AuthenticationListener (SessionEvents.AuthListener) to the SessionEvents.

The following code (wrapper method) illustrates this :

  • in case of logged in user simply post the message in the background thread.
  • in case of an anonymous user, we wait for the authentication to succeed, and then continue on to posting the message in the background thread.
	public void postMessage() {
		if (facebookConnector.getFacebook().isSessionValid()) {
			postMessageInThread();
		} else {
			SessionEvents.AuthListener listener = new SessionEvents.AuthListener() {

				@Override
				public void onAuthSucceed() {
					postMessageInThread();
				}

				@Override
				public void onAuthFail(String error) {

				}
			};
			SessionEvents.addAuthListener(listener);
			facebookConnector.login();
		}
	}

The clearCredentials() method is responsible for logoff functionality. All credentials are cleared from the system, and each interaction with Facebook will again trigger a login().

	private void clearCredentials() {
		try {
			facebookConnector.getFacebook().logout(getApplicationContext());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

Conclusion

The Android Facebook SDK provides an easy way to integrate Facebook into your Android application. It provides single sign on capabilities, preventing the user from having to login again if a session was already established with Facebook. Also, the OAuth 2.0 implementation that Facebook offers enables a much simpler authentication / authorization mechanism that with traditional OAuth based providers. After having setup the test account to do your testing, you should be up & running with facebook in your application in no time.

References

Categories: Facebook SDK Tags: , , ,
  1. chamith
    March 17th, 2011 at 13:46 | #1

    Hi ddewaele,

    Thanks for you post. But the thing is I’m new to android and I didn’t understand this properly.
    If u can mail me the source code it is very useful to me. I only use it as a reference to my academic works.

    Thanks.

  2. chamith
    March 18th, 2011 at 06:09 | #3

    Thanks A lot.

  3. Zakhar
    March 19th, 2011 at 16:25 | #4

    This example has some necessary folders missing and hence not working. Why don’t you just put whole code there?

  4. admin
    March 20th, 2011 at 16:22 | #5

    @Zakhar
    All source code for the article is present in the github repository. The only thing that is not included in that repository is the Android FaceBook SDK project.
    The Android Facebook SDK project has its own repository at Github located here : https://github.com/facebook/facebook-android-sdk.git
    (The facebook SDK github repository does not come with eclipse .project and .classpath files, so you cannot import it as an existing project, rather you can import it as a new Android project based on existing sources).
    After importing both projects in your IDE, you can link the Android Facebook SDK project to the Facebook Sample as a library project (described in the article.).
    If you’re still having issues importing the code let me know.

  5. March 21st, 2011 at 06:06 | #6

    Hi,

    I just had one question. Is it possible to send a friend request from within this example application? I tried using friends dialog in the place of feeds dailog but it threw me error.. Please help.

  6. Piyush
    March 21st, 2011 at 12:02 | #7

    Can you please guide me on how to retrieve the username of the currently logged in user using the graph api requests…I just can’t get it to work. Btw this example of your just worked fine for me. Excellent work. :)

  7. March 22nd, 2011 at 06:32 | #8

    @Piyush

    Make a facebook obj and do a call to “me”

    Facebook fb = new Facebook(appid);
    AsyncFacebookRunner async = new AsyncFacebookRunner(fb);
    async.request(“me”, new SimpleDialogListener());//fetch the response in this dialog listener

  8. Piyush
    March 22nd, 2011 at 12:20 | #9

    I did exactly this only, but i think I did not fetch the response properly in the listener. Can you please tell me what exactly is returned when we make a call to “me” and how do I process it?

  9. March 23rd, 2011 at 01:59 | #10

    @Piyush

    Its in there in the Facebook SDK example found on github.

  10. Piyush
    March 29th, 2011 at 11:43 | #11

    I got it working, thanks a lot. :)

  11. raosl
    April 4th, 2011 at 08:47 | #12

    When I clicked post button i am redirecting to fb site and then there is an error message, error has occured. I put app id in the code. Why is it not working?

  12. Arnold
    April 20th, 2011 at 21:37 | #13

    Hi!

    The Facebook Become Test Account link is broken. Which is the new link, i could not find it, and I made a new page and I cannot convert it. Could you help me?

    Thanks

    • admin
      April 20th, 2011 at 21:51 | #14

      They’ve seen to brought the page offline. You’ll need to use the Graph API to create a test user according to the docs : http://developers.facebook.com/docs/test_users/. As mentioned on that page : Currently one can only create and manage test user accounts via the API described below but in the near future we will be providing access to this via the developer app.

    • admin
      April 20th, 2011 at 21:53 | #15

      I’ll try to update the article ASAP and if I have the time also provide a code snippet on how to create a test account.

  13. Feeder1803
    May 7th, 2011 at 11:19 | #16

    @admin

    Will you update the article soon? I have tried the app but facebook gives an error. I already used your Twitter tutorial and it is fantastic. Update this ASAP please!!!

  14. admin
    May 7th, 2011 at 20:22 | #17

    @Feeder1803
    I’ve posted a new article New way to create test users in Facebook showing how to create test users in Facebook. Were you trying the sample app with a test user you created before ? If so, you should create a test user the new way, and retry the app. You can always post the exact error you are getting here.

  15. deph1lt
    May 11th, 2011 at 07:27 | #18

    can mail me the source code it is very useful to me?

    i’m not understand in declaration
    SessionStore.restore(facebook, context);
    SessionEvents.addAuthListener(mSessionListener);
    SessionEvents.addLogoutListener(mSessionListener);

    thanks alot..

  16. Carrie
    May 11th, 2011 at 21:12 | #20

    I just came across this after banging my head against a wall for a few hours, great example, thanks for posting this :)

  17. Arnold
    May 14th, 2011 at 18:06 | #21

    Hi!

    When I want to create a new app on the given page, I have this message: “Your account must be verified before you can take this action. Please verify your account by adding your mobile phone or credit card.”

    If I try to give my phone, my country is not in the list, and I don’t want to give my credit card, because I don’t want them to have access to my credit card details.

    Thank you, looking forward for your answer

  18. Arnold
    May 14th, 2011 at 18:33 | #22

    I forgot to ask, what should I do in this situation? There are any work arounds?

  19. Thiago
    May 18th, 2011 at 17:14 | #23

    Hi,

    Would you write a 30-minute tutorial on how to integrate Foursquare api into an android app? Many thanks

    T

  20. Balint
    May 31st, 2011 at 20:45 | #24

    private static final String FACEBOOK_APPID = “PUT YOUR FACEBOOfK APP ID HERE”;
    If now i run the app i can share anything with my friends.
    I have the keys and the app id of my app so i replaced the text with the app id.
    Now if i run the app and click the “Post Message on Wall” Facebook starts loading than closes with the app staying open.
    What is wrong with this??

  21. Balint
    May 31st, 2011 at 20:49 | #25

    I forgot to tell:
    1. I haven’t modified anyhing else in the code.
    2. There is no problem when i run app in eclipse.
    (Notwithstanding sometimes it says i am logged into Twitter. I never had a Twitter acc :) )

  22. Maulik Jadvani
    June 15th, 2011 at 11:06 | #26

    @Piyush

    This Will Help You Out, M Sure

    private final class LoginDialogListener implements DialogListener {
    public void onComplete(Bundle values) {
    // System.out.println(“LoginDialogListener”);
    SessionEvents.onLoginSuccess();

    try {
    JSONObject me = new JSONObject(mFacebook.request(“me”));
    fbname = me.getString(“name”);
    first_name = me.getString(“first_name”);

    System.out.println(“Name :: ” + fbname);
    System.out.println(“FName :: ” + first_name);

    JSONObject attachment = new JSONObject();
    attachment.put(“message”, “Hitch”);
    attachment.put(“name”, name);
    attachment.put(“href”, href);
    attachment.put(“description”, first_name+” just checked in at “+name+ ” on Hitch Location: “+city+” Category: Restaurant”);

    JSONObject media = new JSONObject();
    media.put(“type”, “image”);
    media.put(“src”, image);
    media.put(“href”, href);
    attachment.put(“media”, new JSONArray().put(media));

    Bundle params = new Bundle();
    params.putString(“attachment”, attachment.toString());

    JSONObject actionLink = new JSONObject();
    actionLink.put(“text”, “Hitch”);
    actionLink.put(“href”, href);
    JSONArray jasonarray = new JSONArray().put(actionLink);
    params.putString(“action_links”, jasonarray.toString());

    mFacebook.dialog(mActivity, “stream.publish”, params, new SampleDialogListener());

    } catch (Exception ex) {
    ex.printStackTrace();
    }
    }

  23. Rishikesh
    July 5th, 2011 at 05:04 | #27

    Hi, I want to implement like button of facebook in this app. How can we do that

  24. Lucy
    July 11th, 2011 at 14:35 | #28

    Hi

    How do i add a link to a website and possibly an image, at the moment its just text.

    Hope someone can help

    Lucy

    • admin
      July 16th, 2011 at 17:57 | #29

      you can so something like this :

      Bundle params = new Bundle();
      params.putString(“message”, “My Message”);
      params.putString(“name”, “This will appear beside the picture”);
      params.putString(“caption”, “This will appear under the title”);
      params.putString(“description”, “Description”);
      params.putByteArray(“picture”, “http://ref/to/some/picture”);
      mFacebook.request(“me/feed”, params, “POST”);

  25. Kyle Smaagard
    July 11th, 2011 at 14:49 | #30

    Awesome tutorials!!! Although I noticed you haven’t had any in a while, is this site still being updated?

    Also, it appears that some guy over at Android10 is jacking your articles…unless thats you too…

    • admin
      July 16th, 2011 at 17:55 | #31

      Thx … been busy with a lot of other stuff…. Going to post some new articles this weekend and next week.
      Regarding Android10, I also noticed that recently…… Not cool that that they just copy the entire content of my articvles on their site. There is only a small reference to this blog, but I’m sure most of their users have the impression its written by the Adnroid10 people. They copy from a lot of other sites as well. Going to get into contact with them to clear this out.

  26. July 17th, 2011 at 19:01 | #32

    Hello, it doesn’t work if u have official facebook app installed. Can I fix it myself or not?

  27. khruel
    July 19th, 2011 at 09:31 | #33

    Hey, the app is very nice and thanks for the tutorials!

    However! Since I’m a big newbie in Java/Android SDK, I was wondering if you could include some more details/references regarding the SessionStore and SessionEvents. What are they for and how exactly are they working?

    Thanks!

  28. Srini
    July 31st, 2011 at 08:08 | #34

    Hi,

    I want to start a new Activity once the facebook authentication is done. I am trying to do that in “onComplete()” method of the DialogListener:

    public void onComplete(Bundle values) {
    SessionStore.save(facebook, currentActivity);
    if (facebook.getAccessToken() != null) {
    currentActivity.getIntent().putExtra(“ACCESS_TOKEN”, facebook.getAccessToken());
    Intent intent = new Intent(currentActivity, PhoneGapActivity.class);
    intent.putExtra(“ACCESS_TOKEN”, facebook.getAccessToken());
    startActivity(intent);
    }
    }

    But the app is crashing as soon as it opens.

    Any ideas? How do I start a new activity after facebook authentication is done?

  29. Dev
    August 3rd, 2011 at 07:37 | #35

    Thanks a lot man it was just awesome…. :)

  30. August 4th, 2011 at 05:33 | #36

    Can you please guide me on how to retrieve the username of the currently logged in user using the graph api requests…I just can’t get it to work. Btw this example of your just worked fine for me. Excellent work. :)

  31. Mohamed sayed
    August 18th, 2011 at 13:02 | #37

    hii all , am new to android , and i have a problem and i wish any one help me in it , i didn`t change any thing in the code, and when i start the application and press the post button, the application load and then come back to the first activity with no thing , and when i checked the log with the tag facebook-authorize it said that
    Login failed :invalid-key
    how can i solve it ,
    note : i have put my application id

  32. ron
    September 7th, 2011 at 16:53 | #38

    hi, thanks for posting such a nice article…i appreciate your work buddy…i have commeted logout button and put clearcredentials() in tweet.SetOnClickListener()…like,
    tweet.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {

    clearCredentials();
    postMessage();

    }
    });

    now when i run app and click on post message on facebook first time asks for login and post msg one time,in second time asks for login and posts message post on facebook wall but when i click 3rd time asks login and it will post message 3times to facebook wall…and so on….the problem is why it posts msg more than one time?? i have modified any code of yours…as it is…just commented logout button….pls help as early as possible……..THANKS A LOT…

  33. Nony
    September 8th, 2011 at 09:56 | #39

    Whenever I post on my wall or I comment on my friend’s status using facebook mobile (Android)…It is not showing – via android along with that…I can I do that ????

    Please suggest…

  34. swlozano
    September 12th, 2011 at 22:39 | #40

    Muchas Gracias me fue de gran ayuda. Thks

  35. Onur
    September 20th, 2011 at 20:06 | #41

    Hi ddewaele,

    It answered a lot of our questions ! Thank you for the great article :)

    Best.

  36. Raveesh
    September 22nd, 2011 at 09:02 | #42

    How to get the profile picture of the user? Please help me.

  37. Raveesh
    September 23rd, 2011 at 09:22 | #43

    @Srini
    Hi Can u please post ur code here if the issue solved. i want to start another activity as soon as facebook authentication is done.

  38. Seshagiri
    September 28th, 2011 at 14:05 | #44

    Hi, Thanks for the post.
    I want to implement like button or a button performing like funcationality of facebook in my app. How can I do that?

  39. Arun
    October 1st, 2011 at 11:54 | #45

    Hi,

    Thanks a lot for the tutorial. I tried the code on my simulator., it works fine and posts messages on the wall. But when I try to do the same from my phone, no message is posted on the wall.

    Can you please let me know what I am missing.

    Regards
    Arun

  40. Onur
    October 3rd, 2011 at 13:02 | #46

    Hi ddewaele,

    I came across your article while surfing related to SDK article, great post!! Thanks for sharing the code snippet.

    Here is the code, I can see that you implemented both facebook session and Wall posting in the same activity. Do you know how I can implement this in two activities?

    Meaning that in my first activity I created user session by logging him in, I would like to pass that session information to 2nd activity in order to post to wall.

    What do you think? What’s the best way to pass facebook session from one activity to another? (First class to Second class for instance) How this can be implemented?

  41. Onur
    October 3rd, 2011 at 13:02 | #47

    Onur :
    Hi ddewaele,
    I came across your article while surfing related to SDK article, great post!! Thanks for sharing the code snippet.
    Here in the code, I can see that you implemented both facebook session and Wall posting in the same activity. Do you know how I can implement this in two activities?
    Meaning that in my first activity I created user session by logging him in, I would like to pass that session information to 2nd activity in order to post to wall.
    What do you think? What’s the best way to pass facebook session from one activity to another? (First class to Second class for instance) How this can be implemented?

  42. megha
    October 13th, 2011 at 13:07 | #48

    hi i have one issue with facebook android integration
    Bundle parameters = new Bundle();
    parameters.putString(“message”, mes);
    try {
    String response = mFacebook.request(“me/feed”, parameters,”POST”);
    System.out.println(response);
    } catch (IOException e) {
    e.printStackTrace();
    }

    it give me the below error
    Key message expected byte[] but value was a java.lang.String. The default value was returned.
    how to resolve this?

  43. Marc
    October 15th, 2011 at 18:03 | #49

    Im getting a nullpointer exeption

    10-15 18:23:45.855: ERROR/AndroidRuntime(28884): at com.bluemner.WinterzauberApp.WinterzauberMain.updateLoginStatus(WinterzauberMain.java:121)
    10-15 18:23:45.855: ERROR/AndroidRuntime(28884): at com.bluemner.WinterzauberApp.WinterzauberMain.onResume(WinterzauberMain.java:117)

    The two methods are exactly like you did them. Please tell me what I can do

    Thanx Marc

  44. vnshetty
    October 17th, 2011 at 03:47 | #50

    awesome tutorial..your twitter integration worked for me perfectly but im getting webpagenot available error in facebook integration .. and no error in log cat so im stuck in middle pls help me…

  45. worked
    November 23rd, 2011 at 01:11 | #51

    parameters.putString(“message”, msg);

    The “message” property is now deprecated and will not show on the wall. This tut won’t work anymore.

  46. December 16th, 2011 at 08:46 | #52

    I tried your tutorial but it seems that didn’t work well. when i pressed post message on well the emulator only display loading page. what should i do. did i miss something ??

    Thanks

  47. Tom
    December 22nd, 2011 at 01:09 | #53

    @Srini
    Hi Srini,

    I’m looking for the same information. Were you able to find how to keep your Facebook login state when going to a new Activity?

    thanks!

  48. Raveesh
    January 2nd, 2012 at 08:31 | #54

    Single sign on is not working. im testing this code in 2 devices. one is having FB as built in app, another device doesn’t have FB. in second case im getting a login page and i can post the message in my wall. But first case where FB is built in app, unable to post the message on my wall. i checked my logs, no errors over there. Can you please help me to solve the issue?

  49. Meena
    January 23rd, 2012 at 10:13 | #55

    hey ddewaele, ur post seems very helpful..i’hv been trying to integrate FB with android..bt while creating an app after i provided the test app name its giving me error that u r not valid user…so can’t create account..bt actualy i created new gmail account n using the id of which i signed up on FB..can u please tell me where m gng wrong???plssssssss

  50. Meena
    January 23rd, 2012 at 10:20 | #56

    this is the error which they r showing…

    You can no longer create apps because our systems indicated that your account may not be authentic. Facebook requires users to provide their real first and last names, and fake accounts are a violation of our Statement of Rights and Responsibilities (SRR 4.1), even when used to host or test apps. Also note that maintaining multiple accounts, even if they are authentic, is also prohibited. If you would like to create a test user to test app functionality, you can do so here: http://developers.facebook.com/docs/test_users/.

    If you believe you have received this message in error, please submit an appeal: https://www.facebook.com/help/contact_us.php?id=140703502680919

  51. dyesdyes
    February 10th, 2012 at 15:49 | #57

    Hey,

    thanks for this article.

    But clearly, 30 minutes is not even close to the truth. Too complete this thing, you must already know how to do this or what to do.
    You should try to explain a bit more and most of all, detail all the steps.
    Of course, you are going quite fast, but that’s useless if it’s not clear.

    Anyway, good work, was a great help for me.

    Thanks again

  52. Hoang KILIK
    February 22nd, 2012 at 09:27 | #58

    thank for your post. It’s useful for me :D

  53. Damu
    February 23rd, 2012 at 06:37 | #59

    Hello,
    I tried running this app in Galaxy S1. it showing white screen with title of facebook. pls tell me anything else i need to modify.

  54. kony
    February 23rd, 2012 at 12:11 | #60

    is working fine now ?

  55. kony
    February 24th, 2012 at 05:51 | #61

    Hi,
    i am getting the error like “The connection to the server was unsuccessful” for the following URL . https://m.facebook.com/dialog/oauth?display=touch&client_id=114580602003080&scope=publish_stream&type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess..

    Pls help me what i need to do ..

    Thanks.

  56. Damu
    February 24th, 2012 at 09:32 | #62

    Hello,

    This tutorial is nice & helpful …

    Thank you ..

  57. February 25th, 2012 at 10:50 | #63

    I have problem with this code. if i have facebook already in my mobile and signed in means this code doesn’t show the FACEBOOK login page in my application. it suddenly returns into the page where i have started … how to overcome this issue …

    Please Suggest As soon as Possible. Thanks in advance …..

  58. vicky
    March 4th, 2012 at 06:26 | #64

    gr8 info… can you help me about how to retrive user personal and organisational information through user facebook database to my android application database…. mail me….. thanks in advance

  59. March 13th, 2012 at 04:38 | #65

    This article, which I read on android10.org, has been very helpful in integrating facebook into my app. However I didn’t like that android10 is taking credit of this article.

    As for this wonderful tutorial, I have noticed that only the activity which does the sign up can post messages to the wall.

    Now my question is, how can we do so that initiate the login via Preferences and then allow any Activity in the app to post to the wall, and then also allow via the Preferences to logout? I guess logout won’t be an issue since its the same Activity, but how other Activities could access the OAuth and Session credentials in order to post to wall?

    Guidance in this regard would be highly appreciated.

    • admin
      March 25th, 2012 at 13:45 | #66

      I’ve sent an email to the android10.org guys and they promised to take the content down. Also feel that it is inappropriate for them to just copy the entire content of these tutorials and embed them in their site as if they wrote it. Just noticed the content is still available at android10.org so I guess I’ll have to send them a reminder.

      As far as allowing your entire application code access to Facebook, storing the credentials in shared prefs and picking them up from other activities should be sufficient. This is how most apps do it.

  60. deepak
    March 20th, 2012 at 16:17 | #67

    @Alexey Yes I notice that too.

  61. Ashray P. Shetty
    March 26th, 2012 at 07:15 | #68

    I’m developing an application to post the status update to facebook. I’ll send my code can you please help me it’s urgent.

  62. Alexandr
    March 30th, 2012 at 13:59 | #69

    Guys, please help me.

    hot do you get this to work with a phone which already has the Facebook application on it? it simply won’t budge…

  63. Ashray P. Shetty
    April 12th, 2012 at 05:02 | #70

    Even i’m facing the same, if the facebook app is already installed it wont work. I’m even confused how to implement the call back url to get this work. Pls can any one help?

  64. Nitesh
    April 12th, 2012 at 05:48 | #71

    I get these errors. Please help me

    04-12 12:45:06.716: W/dalvikvm(464): VFY: unable to find class referenced in signature (Lcom/facebook/android/Facebook;)

    04-12 12:45:06.716: I/dalvikvm(464): Could not find method com.facebook.android.Facebook.logout, referenced from method com.ecs.android.facebook.Sample.AndroidFacebookSample.clearCredentials

    04-12 12:45:06.746: W/dalvikvm(464): VFY: unable to resolve virtual method 120: Lcom/facebook/android/Facebook;.logout (Landroid/content/Context;)Ljava/lang/String;

    04-12 12:45:06.746: D/dalvikvm(464): VFY: replacing opcode 0x6e at 0x000a

    04-12 12:45:06.746: W/dalvikvm(464): VFY: unable to find class referenced in signature (Lcom/facebook/android/Facebook;)

    04-12 12:45:06.796: I/dalvikvm(464): Could not find method com.facebook.android.Facebook.authorizeCallback, referenced from method com.ecs.android.facebook.Sample.AndroidFacebookSample.onActivityResult

    04-12 12:45:06.796: W/dalvikvm(464): VFY: unable to resolve virtual method 116: Lcom/facebook/android/Facebook;.authorizeCallback (IILandroid/content/Intent;)V

    04-12 12:45:06.827: D/dalvikvm(464): VFY: replacing opcode 0x6e at 0×0006

    04-12 12:45:06.827: D/dalvikvm(464): VFY: dead code 0×0009-0009 in Lcom/ecs/android/facebook/Sample/AndroidFacebookSample;.onActivityResult (IILandroid/content/Intent;)V

    04-12 12:45:06.846: W/dalvikvm(464): VFY: unable to find class referenced in signature (Lcom/facebook/android/Facebook;)

    04-12 12:45:06.846: I/dalvikvm(464): Could not find method com.facebook.android.Facebook.isSessionValid, referenced from method com.ecs.android.facebook.Sample.AndroidFacebookSample.postMessage

    04-12 12:45:06.886: W/dalvikvm(464): VFY: unable to resolve virtual method 119: Lcom/facebook/android/Facebook;.isSessionValid ()Z

    04-12 12:45:06.886: D/dalvikvm(464): VFY: replacing opcode 0x6e at 0×0006

    04-12 12:45:06.886: D/dalvikvm(464): VFY: dead code 0×0009-001d in Lcom/ecs/android/facebook/Sample/AndroidFacebookSample;.postMessage ()V

    04-12 12:45:06.897: W/dalvikvm(464): VFY: unable to find class referenced in signature (Lcom/facebook/android/Facebook;)

    04-12 12:45:06.906: I/dalvikvm(464): Could not find method com.facebook.android.Facebook.isSessionValid, referenced from method com.ecs.android.facebook.Sample.AndroidFacebookSample.updateLoginStatus

    04-12 12:45:06.906: W/dalvikvm(464): VFY: unable to resolve virtual method 119: Lcom/facebook/android/Facebook;.isSessionValid ()Z

    04-12 12:45:06.916: D/dalvikvm(464): VFY: replacing opcode 0x6e at 0x000f

    04-12 12:45:06.916: D/dalvikvm(464): VFY: dead code 0×0012-001e in Lcom/ecs/android/facebook/Sample/AndroidFacebookSample;.updateLoginStatus ()V

    04-12 12:45:06.986: E/dalvikvm(464): Could not find class ‘com.facebook.android.Facebook’, referenced from method com.ecs.android.facebook.Sample.FacebookConnector.

    04-12 12:45:06.986: W/dalvikvm(464): VFY: unable to resolve new-instance 45 (Lcom/facebook/android/Facebook;) in Lcom/ecs/android/facebook/Sample/FacebookConnector;

    04-12 12:45:06.986: D/dalvikvm(464): VFY: replacing opcode 0×22 at 0x000d

    04-12 12:45:06.986: D/dalvikvm(464): VFY: dead code 0x000f-0030 in Lcom/ecs/android/facebook/Sample/FacebookConnector;. (Ljava/lang/String;Landroid/app/Activity;Landroid/content/Context;[Ljava/lang/String;)V

    04-12 12:45:06.996: W/dalvikvm(464): VFY: unable to find class referenced in signature (Lcom/facebook/android/Facebook;)

    04-12 12:45:06.996: W/dalvikvm(464): VFY: unable to find class referenced in signature (Lcom/facebook/android/Facebook;)

    04-12 12:45:06.996: I/dalvikvm(464): Could not find method com.facebook.android.Facebook.isSessionValid, referenced from method com.ecs.android.facebook.Sample.FacebookConnector.login

    04-12 12:45:07.006: W/dalvikvm(464): VFY: unable to resolve virtual method 119: Lcom/facebook/android/Facebook;.isSessionValid ()Z

    04-12 12:45:07.006: D/dalvikvm(464): VFY: replacing opcode 0x6e at 0×0002

    04-12 12:45:07.006: D/dalvikvm(464): VFY: dead code 0×0005-0017 in Lcom/ecs/android/facebook/Sample/FacebookConnector;.login ()V

    04-12 12:45:07.006: E/dalvikvm(464): Could not find class ‘com.facebook.android.AsyncFacebookRunner’, referenced from method com.ecs.android.facebook.Sample.FacebookConnector.logout

    04-12 12:45:07.006: W/dalvikvm(464): VFY: unable to resolve new-instance 42 (Lcom/facebook/android/AsyncFacebookRunner;) in Lcom/ecs/android/facebook/Sample/FacebookConnector;

    04-12 12:45:07.006: D/dalvikvm(464): VFY: replacing opcode 0×22 at 0×0003

    04-12 12:45:07.006: D/dalvikvm(464): VFY: dead code 0×0005-0014 in Lcom/ecs/android/facebook/Sample/FacebookConnector;.logout ()V

    04-12 12:45:07.006: I/dalvikvm(464): Could not find method com.facebook.android.Facebook.isSessionValid, referenced from method com.ecs.android.facebook.Sample.FacebookConnector.postMessageOnWall

    04-12 12:45:07.006: W/dalvikvm(464): VFY: unable to resolve virtual method 119: Lcom/facebook/android/Facebook;.isSessionValid ()Z

    04-12 12:45:07.006: D/dalvikvm(464): VFY: replacing opcode 0x6e at 0×0002

    04-12 12:45:07.016: D/dalvikvm(464): VFY: dead code 0×0005-002a in Lcom/ecs/android/facebook/Sample/FacebookConnector;.postMessageOnWall (Ljava/lang/String;)V

    04-12 12:45:07.016: D/AndroidRuntime(464): Shutting down VM

    04-12 12:45:07.016: W/dalvikvm(464): threadid=1: thread exiting with uncaught exception (group=0×40015560)

    04-12 12:45:07.026: E/AndroidRuntime(464): FATAL EXCEPTION: main

    04-12 12:45:07.026: E/AndroidRuntime(464): java.lang.NoClassDefFoundError: com.facebook.android.Facebook

    04-12 12:45:07.026: E/AndroidRuntime(464): at com.ecs.android.facebook.Sample.FacebookConnector.(FacebookConnector.java:28)

    04-12 12:45:07.026: E/AndroidRuntime(464): at com.ecs.android.facebook.Sample.AndroidFacebookSample.onCreate(AndroidFacebookSample.java:40)

    04-12 12:45:07.026: E/AndroidRuntime(464): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)

    04-12 12:45:07.026: E/AndroidRuntime(464): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)

    04-12 12:45:07.026: E/AndroidRuntime(464): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)

    04-12 12:45:07.026: E/AndroidRuntime(464): at android.app.ActivityThread.access$1500(ActivityThread.java:117)

    04-12 12:45:07.026: E/AndroidRuntime(464): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)

    04-12 12:45:07.026: E/AndroidRuntime(464): at android.os.Handler.dispatchMessage(Handler.java:99)

    04-12 12:45:07.026: E/AndroidRuntime(464): at android.os.Looper.loop(Looper.java:130)

    04-12 12:45:07.026: E/AndroidRuntime(464): at android.app.ActivityThread.main(ActivityThread.java:3683)

    04-12 12:45:07.026: E/AndroidRuntime(464): at java.lang.reflect.Method.invokeNative(Native Method)

    04-12 12:45:07.026: E/AndroidRuntime(464): at java.lang.reflect.Method.invoke(Method.java:507)

    04-12 12:45:07.026: E/AndroidRuntime(464): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)

    04-12 12:45:07.026: E/AndroidRuntime(464): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)

    04-12 12:45:07.026: E/AndroidRuntime(464): at dalvik.system.NativeStart.main(Native Method)

  65. Nitesh
    April 12th, 2012 at 08:02 | #72

    sorry….just got it run….there was problem in including com_facebook_android. thanks for awsome tutorial. i have used your twitter tutorial as well…they both save me from big trouble. keep writing tutorial :)
    Thanks again

  66. kamal
    April 12th, 2012 at 12:25 | #73

    on clicking “Facebook Become Test Account” get message of page not available…

  67. Anna
    April 12th, 2012 at 23:36 | #74

    I studied the “30 minutes guide to integrating Facebook in Android application”.
    I am having a problem adding the com_facebook_android to my Android project “AndroidFacebook”. When I clicked on the “Add” button, I do not see the facebook library listed there.

    My facebook library is located at C:\Documents and Settings\user\git\facebook-android-sdk
    My Android project is located at C:\Documents and Settings\user\workspace\AndroidFacebook
    Please help as soon as possible. Thank you in advance for your kindness.

  68. Nick
    April 19th, 2012 at 08:40 | #75

    Target “${build.target}” does not exist in the project “facebook”.
    that’s as far as I can get, tis happens at the end of the build. I also had an issue with the sdk target not being set because the lack of local.properties file. Couldn’t find Android Update command tool, don’t know where that is. So I set it in the properties.properties file instead that got rid of that error. Now I’m stuck n the build.target error, I have also specified the targets in the manifest. It would be far simpler to have a library rather than an incomplete project directory.

  69. Matt
    April 19th, 2012 at 19:55 | #76

    @Anna
    Hello, I’m having this exact same problem and its driving me insane. Did you find a solution? Thanks!

  70. Sourabh Sahu
    May 2nd, 2012 at 11:19 | #77

    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {
    messageSender = new Messenger(service);
    refreshToken();
    }

    @Override
    public void onServiceDisconnected(ComponentName arg) {
    serviceListener.onError(new Error(“Service disconnected”));
    // We returned an error so there’s no point in
    // keeping the binding open.
    applicationsContext.unbindService(TokenRefreshServiceConnection.this);
    }

    these two methods throwing some error…please suggest some thing..

  71. May 21st, 2012 at 07:23 | #78

    Hi ddewaele,

    Thanks for this tutorial. It works !
    I tried to upload photo by modifying your code as follow :

    byte[] imgData = getImage(“http://bandungraos.in/wp-content/resto/1/gallery/kepiting1.jpg”);
    parameters.putByteArray(“picture”, imgData);
    try {
    //String response = facebook.request(“me/feed”, parameters,”POST”);
    String response = facebook.request(“me/photos”, parameters,”POST”);
    System.out.println(response);
    } catch (IOException e) {

    }

    …..

    private byte[] getImage(String url) {

    try {
    URL imgUrl = new URL(url);
    HttpURLConnection cn = (HttpURLConnection) imgUrl.openConnection();
    cn.setDoInput(true);
    cn.connect();
    int length = cn.getContentLength();
    byte[] imgData = new byte[length];
    InputStream is = cn.getInputStream();
    is.read(imgData);
    return imgData;

    } catch (MalformedURLException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }

    return null;

    }
    }

    There is no error but the photo was not uploaded to facebook

    Would you help me?

    thanks

  72. Liza
    January 18th, 2013 at 04:59 | #79

    Hi thanks for sharing this awesome post with all of us, and i believe that you will make many more,

    but here i urge you to make a program in which we allow user to do login and user will get list of all friends – Month wise, Week wise, Today [Current Date Wise], In list friends name is enough.

    I hope you have made that already, but here i am requesting you to share with us..It’s Urgent…….. and for you and your tutorials [No one can define you, no one able to judge your tuts..... Great Dude.... God Bless You] :)

  73. Harsha
    March 2nd, 2013 at 09:04 | #80

    Your Artical is Good, Problem with my Understanding.
    I have an Activity with edittext and facebook share image.
    Enter some text into that edittext and after click facebook share how to handle.please help me little bit confuse.

  74. Harsha
    March 2nd, 2013 at 09:06 | #81

    Harsha :
    Your Artical is Good, Problem with my Understanding.
    I have an Activity with edittext and facebook share image.
    Enter some text into that edittext and after click facebook share how to share that edittext text in to facebook. please help me little bit confuse.

  75. Sruthi
    April 2nd, 2013 at 19:23 | #82

    Hello,
    I imported the project from github directly.But I got some errors.Then I added facebook-sdk.jar file in libs folder.Then errors are solved but When I run Unfortunately,app has stopped is coming.and NoClassDef found is coming in logcat.Please Can you help me how to solve this problem?
    Can you explain in detail(Step-by-Step).Thanks in advance.Awaiting your reply.

  76. Ashish
    April 12th, 2013 at 06:48 | #83

    How to login from existing official facebook application if already installed in device,

  77. anoo
    April 13th, 2013 at 09:35 | #84

    This uses post request, but the new one is graph api. Can you update it please?

  78. Nitu
    April 16th, 2013 at 14:54 | #85

    Hi All,
    I downloaded the facebook android Sdk from the link specified in this article but I get an error in the PickerFragment file`s attach method – invalid type for LoadingStrategy . Don’t understand why. Any help is appreciated.

    Thanks

  79. Rahul Goel
    April 25th, 2013 at 12:30 | #86

    But this message is only seen on my wall. my friends are not able to see this message. how i can do this?

  80. Raamkum
    May 2nd, 2013 at 01:35 | #87

    Thanks for the tutorial but this doesn’t work with the latest FB SDk 3.0.

    The other issue with old sdk is that? If the fb is logout from FB app in phone my app also log’s out. I believe 3.0 is independent and doesn’t care of FB app login or logout.

    Can you put a tutorial with the latest SDK please?

    Thanks!

  1. May 7th, 2011 at 20:00 | #1
  2. March 18th, 2013 at 14:51 | #2