This tutorial is about integrating facebook into your android application. I am going to explain various steps like generating your application signature, registering facebook application, downloading facebook sdk and other steps. Here is an official documentation of facebook integration.

Download Code

Generating App Signature for Facebook Settings

To create facebook android native app you need to provide your Android application signature in facebook app settings. You can generate your application signature (keyhash) using keytool that comes with java. But to generate signature you need openssl installed on your pc. If you don’t have one download openssl from here and set it in your system environment path.

Open your command prompt (CMD) and run the following command to generate your keyhash. While generating hashkey it should ask you password. Give password as android. If it don’t ask for password your keystore path is incorrect.

keytool -exportcert -alias androiddebugkey -keystore "<path-to-users-directory>\.android\debug.keystore" | openssl sha1 -binary | openssl base64

check the following command how i generated hashkey on my pc.

keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Ravi\.android\debug.keystore" | openssl sha1 -binary | openssl base64
android facebook generating hash key app signature

Registering your Facebook Application

After generating your app signature successfully, register your facebook application by going to create new facebook application and fill out all the information needed. And select Native Android App and give your hashkey there which you generated previously using keytool.

android facebook register app

and note down your facebook App ID

android facebook app id

Creating Facebook Reference Project

Once you are done with registering your facebook application, you need to download facebook SDK and create a new reference project. This reference project will be used to compile your actual project.

1. Download facebook android SDK from git repositories.
(git clone git://github.com/facebook/facebook-android-sdk.git)

2. In your Eclipse goto File ⇒ Import ⇒ Existing Projects into Workspace and select the facebook project you downloaded from git repository.

android facebook import project

Creating Your Facebook Connect Project

1. Create new Project in your Eclipse IDE. File ⇒ New ⇒ Android Project and fill out all the details.

2. Now we need to add reference of this project to existing facebook project. Right Click on Project ⇒ Properties ⇒ android ⇒ Click on Add button ⇒ select your facebook project ⇒ Click Apply.

android facebook adding reference project
android facebook adding reference project
android facebook adding reference project

Now our project setup is done. We can start coding our facebook application.

3. Open your AndroidManifest.xml file add network connect permission in order to connect to internet.

<uses-permission android:name="android.permission.INTERNET"/>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.facebook.androidhive"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".AndroidFacebookConnectActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

    <!-- Connect to Internet Permissions -->
    <uses-permission android:name="android.permission.INTERNET"/>

</manifest>

4. Open Your Main Activity Class and initialize all the variables needed.

public class AndroidFacebookConnectActivity extends Activity {

	// Your Facebook APP ID
	private static String APP_ID = "308180782571605"; // Replace your App ID here

	// Instance of Facebook Class
	private Facebook facebook;
	private AsyncFacebookRunner mAsyncRunner;
	String FILENAME = "AndroidSSO_data";
	private SharedPreferences mPrefs;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		facebook = new Facebook(APP_ID);
		mAsyncRunner = new AsyncFacebookRunner(facebook);

5. I created a simple interface which contains button to login, post to wall, show access tokens and logout for testing purpose.

Login to Facebook Account

I used a button to login into facebook account. In your activity write a click event for Login button click. Inside click event declare a function named loginToFacebook();

Login button click event

btnFbLogin.setOnClickListener(new View.OnClickListener() {
	@Override
	public void onClick(View v) {
			loginToFacebook();
		}
});

and function body for loginToFacebook() function is:

	public void loginToFacebook() {
		mPrefs = getPreferences(MODE_PRIVATE);
		String access_token = mPrefs.getString("access_token", null);
		long expires = mPrefs.getLong("access_expires", 0);

		if (access_token != null) {
			facebook.setAccessToken(access_token);
		}

		if (expires != 0) {
			facebook.setAccessExpires(expires);
		}

		if (!facebook.isSessionValid()) {
			facebook.authorize(this,
					new String[] { "email", "publish_stream" },
					new DialogListener() {

						@Override
						public void onCancel() {
							// Function to handle cancel event
						}

						@Override
						public void onComplete(Bundle values) {
							// Function to handle complete event
							// Edit Preferences and update facebook acess_token
							SharedPreferences.Editor editor = mPrefs.edit();
							editor.putString("access_token",
									facebook.getAccessToken());
							editor.putLong("access_expires",
									facebook.getAccessExpires());
							editor.commit();
						}

						@Override
						public void onError(DialogError error) {
							// Function to handle error

						}

						@Override
						public void onFacebookError(FacebookError fberror) {
							// Function to handle Facebook errors

						}

					});
		}
	}
android facebook login

Posting Message to Facebook Wall

write a click event for post to wall button and inside click event write a function named postToWall()

btnPostToWall.setOnClickListener(new View.OnClickListener() {
	@Override
	public void onClick(View v) {
		postToWall();
	}
});

and function body for postToWall() function is:

	public void postToWall() {
		// post on user's wall.
		facebook.dialog(this, "feed", new DialogListener() {

			@Override
			public void onFacebookError(FacebookError e) {
			}

			@Override
			public void onError(DialogError e) {
			}

			@Override
			public void onComplete(Bundle values) {
			}

			@Override
			public void onCancel() {
			}
		});

	}
android facebook posting to wall
android facebook posting to wall test

Getting Profile Information from Facebook

To get profile information we need to make an api request to facebook graph API. Following is a function that will make an api request to facebook profile graph api and will get profile information from facebook.

getProfileInformation()
	public void getProfileInformation() {
		mAsyncRunner.request("me", new RequestListener() {
			@Override
			public void onComplete(String response, Object state) {
				Log.d("Profile", response);
				String json = response;
				try {
					JSONObject profile = new JSONObject(json);
					// getting name of the user
					String name = profile.getString("name");
					// getting email of the user
					String email = profile.getString("email");

					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
						}

					});

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onIOException(IOException e, Object state) {
			}

			@Override
			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
			}

			@Override
			public void onMalformedURLException(MalformedURLException e,
					Object state) {
			}

			@Override
			public void onFacebookError(FacebookError e, Object state) {
			}
		});
	}

The above function will get json data from facebook. You need to parse the json in order to get individual profile data. If you are not aware of json parsing look at this article. Android JSON Parsing Tutorial.

The sample profile json from facebook will be like this

{
   "id": "1464730016",
   "name": "Ravi Tamada",
   "first_name": "Ravi",
   "last_name": "Tamada",
   "link": "https://www.facebook.com/ravi8x",
   "username": "ravi8x",
   "birthday": "12/22/1988",
   "hometown": {
      "id": "112158005464147",
      "name": "Baruva"
   },
   "location": {
      "id": "102186159822587",
      "name": "Chennai, Tamil Nadu"
   },
   "bio": "Author: www.androidhive.info\r\nCo-author: www.9lessons.info",
   "work": [
      {
         "employer": {
            "id": "179366562092719",
            "name": "ByteAlly"
         },
         "location": {
            "id": "102186159822587",
            "name": "Chennai, Tamil Nadu"
         },
         "position": {
            "id": "124917314217511",
            "name": "Product Head"
         }
         ]
      }
   ],
   "favorite_athletes": [
      {
         "id": "18620649907",
         "name": "Virat Kohli"
      }
   ],
   "education": [
      {
         "school": {
            "id": "131587206873093",
            "name": "Raghu Engineering College (REC)"
         },
         "degree": {
            "id": "140065339390579",
            "name": "B.Tech"
         },
         "year": {
            "id": "142963519060927",
            "name": "2010"
         },
         "type": "Graduate School",
         "classes": [
            {
               "id": "192259410803415",
               "name": "2010",
               "with": [
                  {
                     "id": "584960408",
                     "name": "Santosh Patnaik"
                  }
               ],
               "from": {
                  "id": "584960408",
                  "name": "Santosh Patnaik"
               }
            }
         ]
      }
   ],
   "gender": "male",
   "relationship_status": "Single",
   "website": "www.androidhive.info\nwww.9lessons.info\nwww.twitter.com/ravitamada\nwww.about.me/rv",
   "timezone": 5.5,
   "locale": "en_US",
   "languages": [
      {
         "id": "106059522759137",
         "name": "English"
      },
      {
         "id": "107617475934611",
         "name": "Telugu"
      },
      {
         "id": "112969428713061",
         "name": "Hindi"
      },
      {
         "id": "343306413260",
         "name": "Tamil"
      }
   ],
   "verified": true,
   "updated_time": "2012-03-02T17:04:18+0000"
}

Extending facebook Permissions

If you want user’s other information like checkins, friends list etc., you need to extend facebook permissions while logging in user. Check list of facebook permissions

facebook.authorize(this, new String[] { "email", "publish_checkins", "publish_stream" },

      new DialogListener() {
           @Override
           public void onComplete(Bundle values) {}

           @Override
           public void onFacebookError(FacebookError error) {}

           @Override
           public void onError(DialogError e) {}

           @Override
           public void onCancel() {}
      }
);

Getting Access Token

Sometimes you might needed users access token for future purpose usage. Following code will give you currently logged in user access token.

String access_token = facebook.getAccessToken();

Logout from your app

When user want to stop using facebook for your app, you can provide logout method to clear app state and invalidate access token. So further you can’t make request to facebook from your app.

logoutFromFacebook();
	public void logoutFromFacebook() {
		mAsyncRunner.logout(this, new RequestListener() {
			@Override
			public void onComplete(String response, Object state) {
				Log.d("Logout from Facebook", response);
				if (Boolean.parseBoolean(response) == true) {
					// User successfully Logged out
				}
			}

			@Override
			public void onIOException(IOException e, Object state) {
			}

			@Override
			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
			}

			@Override
			public void onMalformedURLException(MalformedURLException e,
					Object state) {
			}

			@Override
			public void onFacebookError(FacebookError e, Object state) {
			}
		});
	}
This image is for thumbnail purpose
android facebook connect
Subscribe
Notify of
guest
350 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
JADEJA SIDDHARAJSINH
JADEJA SIDDHARAJSINH
8 years ago

I Tried but after click on Button it is not loading facebook just loading image is continuously displayed, can any one sugges what is wrong with me?

Mohsin Muhammad Aaheer
Mohsin Muhammad Aaheer
8 years ago

I have completely followed this tutorial, got hash key, created facebook app,
got fb key and put it in your app.
but when I run your app project in your download zip, after running it shows first screen, button on screen to login facebook, when I press that button the app crashed???
why??
please help?
why don’t it connects with my fb app and post status their as your are posing in tutorial?

sangu
sangu
8 years ago

plz help me any one..
how to get the list of active friends,

and the list of friends of selected friend..?

Qadir Hussain
8 years ago

First I would like to appreciate your awesome work. Now coming to my problem I m getting this response while getting the profile. {“error”:{“message”:”An active access token must be used to query information about the current user.”,”type”:”OAuthException”,”code”:2500}} . what should I do. I am following your tutorial step by step. I m sure that I have not missed any of step described. Also please tell me the new classes. Some of them are deprecated now. Thanks

Praveen Mylavarapu
Praveen Mylavarapu
8 years ago

Hi, I am a beginner. Should we upload the app in google play or on fb ??

prashant
prashant
8 years ago

me also getting the same error..struck here

Oliver Jordan
Oliver Jordan
8 years ago

Hi ravi thank you for the tutorial, it works fine on me. Now after login i want to make my app displays the list of my groups on facebook. Is it possible? if yes, would you show me the way to do that? pleaseee 🙂

thanks in advance

Raghava Burugadda
8 years ago

when im logouting it gives exception

Dinesh Bagvan
Dinesh Bagvan
8 years ago

thats very good ….

Stefano Occhi
Stefano Occhi
8 years ago

hi! this is the best tutorial, but i have a problem! I could do the first login with my facebook account, but, now, on the others login i receive an error from facebook page on the app: “Invalid android_key parameter. The key Vp1b———G4TI does not match any allowed key. Configure your app key hashes at http://developers.facebook……/apps/139—– “. I don’t understand this error, because the key cited is not my hash key and why the first login went well?? i think the app is configured well!

Stefano Occhi
Stefano Occhi
8 years ago
Reply to  Stefano Occhi

Up!

hadson
hadson
8 years ago

TNX man… uffff

seenu
seenu
8 years ago

can publish an article about facebook login with mysql?

Jonathan Besinan
Jonathan Besinan
8 years ago

Hi Sir, thanks for the tutorial. It’s really great! is it possible to connect facebook chat in android application?

tushar
tushar
8 years ago

There is phrase , for you in my dictionary …. you are helping millions of people in this world , thanks !

KT
KT
8 years ago

How can i post msg to fb wall when a user clicks on a button ?

Faiza Saleem
Faiza Saleem
8 years ago

gr8 work.. keep it up

Bhavin Doshi
Bhavin Doshi
8 years ago

Good tutorail !

Mit Bhatt
Mit Bhatt
8 years ago

Thanks…. 🙂

Mukesh Garg
Mukesh Garg
8 years ago

Thanks for such a gr8 tutorial . really it was very helpful. could u post a tutorial for Facebook Like through Android ?

Goutam Kundu
Goutam Kundu
8 years ago
Reply to  Mukesh Garg

The same mukesh from palle tech ………..goutam here look like facebook work is going on

nitin
nitin
8 years ago

thanq…it is very usefull…..

Erwandy 林棋良
Erwandy 林棋良
8 years ago

Thank u very much for the code…

But, I have a question.
Actually, how is the way to logout?

I hv tried the logout code above, it’s worked. But, when I clicked for my login button, it always runs successfully on getting access as a logged-in user.
so, I think it has no differences between I log out and I log in…

Thanks before…
Please kindly explain more detail for the way of logout session.
Thank u so much…
=)

Faraz
Faraz
8 years ago

when i first time logs in then it shows Error and a okay button when click on okay button it redirects to login with facebook button.

sanjay sawan
sanjay sawan
8 years ago

can u tell me how can make a application which support the voice password protected…if u have any suggestion regarding this plz inform me at [email protected]..

Kavi ManiKumar
Kavi ManiKumar
8 years ago

Good tutorial…….Thankq…..

Arpit
Arpit
8 years ago

When i click on login with facebook button, it shows a dialog box then came back to same screen

Felipe
Felipe
8 years ago
Reply to  Arpit

same problem

Felipe
Felipe
8 years ago
Reply to  Felipe

The problem was that the facebook app was set to sandbox mode, so only developer accounts could get access token from app’s ID. It works to me.

Rahul Arora
Rahul Arora
8 years ago

How can we get Friends list and their B’day list using this tutorial??? plz help me…

srikanth gutti
srikanth gutti
8 years ago

trying this FB example with new FB SDK 3.0.2 getting error here i am placing the log details.how to fix this
08-16 01:00:41.652: E/AndroidRuntime(4420): FATAL EXCEPTION: main
08-16 01:00:41.652: E/AndroidRuntime(4420): java.lang.NoClassDefFoundError: com.facebook.android.Facebook
08-16 01:00:41.652: E/AndroidRuntime(4420): at com.facebook.androidhive.AndroidFacebookConnectActivity.(AndroidFacebookConnectActivity.java:33)
08-16 01:00:41.652: E/AndroidRuntime(4420): at java.lang.Class.newInstanceImpl(Native Method)
08-16 01:00:41.652: E/AndroidRuntime(4420): at java.lang.Class.newInstance(Class.java:1409)
08-16 01:00:41.652: E/AndroidRuntime(4420): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
08-16 01:00:41.652: E/AndroidRuntime(4420): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1565)
08-16 01:00:41.652: E/AndroidRuntime(4420): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
08-16 01:00:41.652: E/AndroidRuntime(4420): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-16 01:00:41.652: E/AndroidRuntime(4420): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
08-16 01:00:41.652: E/AndroidRuntime(4420): at android.os.Handler.dispatchMessage(Handler.java:99)
08-16 01:00:41.652: E/AndroidRuntime(4420): at android.os.Looper.loop(Looper.java:130)
08-16 01:00:41.652: E/AndroidRuntime(4420): at android.app.ActivityThread.main(ActivityThread.java:3687)
08-16 01:00:41.652: E/AndroidRuntime(4420): at java.lang.reflect.Method.invokeNative(Native Method)
08-16 01:00:41.652: E/AndroidRuntime(4420): at java.lang.reflect.Method.invoke(Method.java:507)
08-16 01:00:41.652: E/AndroidRuntime(4420): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
08-16 01:00:41.652: E/AndroidRuntime(4420): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
08-16 01:00:41.652: E/AndroidRuntime(4420): at dalvik.system.NativeStart.main(Native Method)

ugur
ugur
8 years ago

very thanks useful tutorial. i want a question. my language Turkish. But i’m get string english. example: i get string gender famale, but i convert my language. how i do?

bobby
bobby
8 years ago

when I try to this its showing me error of some link

rado
rado
8 years ago

Please how can I change login fragment to fullscreen?

Trollzito
Trollzito
8 years ago

ok nice!

Mahivardhan Singh
Mahivardhan Singh
8 years ago

Ravi Tamada is my guru(Teacher) of android…thnks ravi

Guru Prasad
Guru Prasad
8 years ago

Hi Sir when i ma going to integret to my app i am getting SharedPreferences error..bcz u are retrving access token from mpref before its creating ..pls let me knw as soon as possible…pls give me reply to my email ……………[email protected]

GaneshKumar B
GaneshKumar B
8 years ago

Great tutorial..I need to get my own mobile number while login.How can it be..?

Sathish
Sathish
8 years ago

HI this is very nice tutorial… I have one doubt, How to get “hometown”, “location” and etc… I am not getting the response for “hometown”, “location” and etc…

Ravi Tamada
8 years ago
Reply to  Sathish

If user filled these details in their profile, then only you will get the response. Otherwise those values won’t be there in the response.

Sathish
Sathish
8 years ago
Reply to  Ravi Tamada

Thanks. Now I got the “hometown”, “location”. My facebook account has user image, mobile number, birthday and address. I am not getting the “address”, “birthday” and “mobile number” and “user image”.

mangesh kaduskar
mangesh kaduskar
8 years ago

I already have Facebook android app in my mobile. And when i try to use my application using Facebook log in integration with this example it doesn’t give me any response.
Please help me.

suresh kumar
suresh kumar
8 years ago

Hi the code works fine in emulator but fails in real device.

shivaprakash
shivaprakash
8 years ago

Its working fine for me. One thing I want to know how o post image on wall, instead of text I want to post image.

Guest
Guest
8 years ago

Hi my hash key is not matched error in login facebook.on SOS signin process.kindly leave reply

Harshpreet Singh
Harshpreet Singh
8 years ago

cant install openssl…someone plz help..

Catcha Freeman
Catcha Freeman
7 years ago

have you succeeded? i have a solution

Relin Jose P.M.™
Relin Jose P.M.™
8 years ago

Can Use Strict Mode Thread policy… Refer: http://stackoverflow.com/questions/8258725/strict-mode-in-android-2-2

manish
manish
8 years ago

Download openSSL->Install it->it would usually install in C:OpenSSL

then open cmd and type

cd../../Program Files (enter)

java (enter)

dir (enter)

cd jdk1.6.0_17 (varies with jdk versions)
to check jdk version go to C:/program files/java/jdk_version

cd bin (enter)

keytool -exportcert -alias androiddebugkey -keystore C:UsersShalini.androiddebug.keystore | “C:OpenSSLbinopenssl sha1 -binary | “C:OpenSSLbinopenssl base64 (enter)

Marcos Henrique da Silva
Marcos Henrique da Silva
8 years ago

thanks for this great and easy tutorial!

KD
KD
8 years ago

thanks For this great and easy tutorial ~!=
But how can , send Post message from Programming …

Vova
Vova
8 years ago

Thanks! It works! However many methods are deprecated. How to fix hat?

anaya
anaya
8 years ago

after laoding fb login page does not open…please help me…..

AirJordan
AirJordan
8 years ago

this article should be considered obsolete, because Facebook has obsoleted “facebook” class…. 🙁

ShahNawaz Khan
ShahNawaz Khan
8 years ago

This really has become obsolete. Started using SocialAuth for android but it lacks proper documentation 🙁 please help!!!

Ravi Tamada
8 years ago
Reply to  ShahNawaz Khan

I’ll look into it.

Tahir Mahmood
Tahir Mahmood
8 years ago

not working … no error in code but still not opening … 🙁

Ravi Tamada
8 years ago
Reply to  Tahir Mahmood

This is deprecated I think. Please follow the tutorial on facebook official doc.

I need to update this tutorial yet

ShahNawaz Khan
ShahNawaz Khan
8 years ago

Please provide a tutorial to integrate SocialAuth!
1.Connect to provider
2.Save Access Tokens
3.Update Status
4.Logout

I just cannot find the documentation, You’re my last resort plz help!

350
0
Would love your thoughts, please comment.x
()
x