Simulator Screenshots

Facebook Integration - Android Example

DOWNLOAD SOURCE CODE
 

Related Examples

In this android example we will learn how to integrate facebook sdk to your android project, make facebook user login and post to facebook user wall.

Click here to see documentation given by facebook for android sdk integration.

There are various steps, Now we are going to explain facebook sdk integration step by step.

 

STEP 1:

Create your android app signature required in facebook settings.

 

To integrate facebook sdk in your application , need to submit your android application signature in facebook setting so that facebook can recognize your app calls.

To generate android application signature java will use keytool, keytools are already comes with java installation. you have also required openssl install on your personal computer.

if openssl not installed on your pc you can download it from here.

Before generating keyhash for your application, make keytool/openssl path settings.

 

A. Set keytool path:

 

Right click on my computer -> open system properties -> click Advanced tab ->click on environment variable

open system settings

set environment variable

set environment variable keytool path

 

B.

Download openssl from this link and extract zip files in C drive(or any other location), in my case i taking unzip files in C drive openssl-0.9.8k_WIN32 folder.

 

openssl location

Now again go to create keyhash for your android application.

 

General keytool command to create keyhash value :

 

    keytool -exportcert -alias androiddebugkey -keystore <path-to-users-directory-where-your-keystore-keys-are-saving>\.android\debug.keystore | <openssl-folder-location>\bin\openssl sha1 -binary | <openssl-folder-location>\bin\openssl base64
  

In my case i am using this command to create keyhash value for my application.

open command prompt (CMD) and run the below command to generate keyhash.

    keytool -exportcert -alias androiddebugkey -keystore C:\Users\Kuldeep\.android\debug.keystore | C:\openssl-0.9.8k_WIN32\bin\openssl sha1 -binary | C:\openssl-0.9.8k_WIN32\bin\openssl base64
	 

when you will run this keytool command on command prompt it will ask for password, write password and press enter button , below you will get keyhash value for your application.

get_keyhash_value_by_keytool_command

 

STEP 2:

Register your Facebook App.

 

Now we will create one facebook app and register it. previous steps created keyhash to facebook.

Create facebook application by loging to your face book account and Click on this link.

After opening the facebook page press on "Add a New App" button.

See below images...

 

A. Select android app on facebook page.

 

create facebook app android

 

B.

Give a name to your facebook app.

 

android facebook app

 

C. Create Facebook APP ID for your app.

 

create facebook app android

 

D.

Submit previous steps created your app keyhash value to your facebook app setting page.

 

make keyhash setting in facebook

Now configuration on facebook ends you are ready to make your app coding part.

Note your Fcaebook created APP ID, It will required to connect with your app.

 

STEP3 :

Now going to create facebook project using eclipse.

 

Project Structure :

facebook connect project structure

Now you have registered facebook application.

 

1.

Now download facebook SDK (Used it as library project).

 

Click on this link to download facebook sdk directly from facebook Or Click on this link facebook download page and download facebook-android-sdk-3.5.1.zip).

 

2.

Save downloaded facebook SDK , extract it and Import downloaded facebook sdk in eclipse.

 

GO TO File -> Import -> Existing Projects into Workspace

import facebook sdk eclipse

Now you will see in project explorer one FacebookSDK name library project created. we will use this facebook SDK library project in main project.

 

STEP4 :

Now create your main project

 

 

1.

Now create new project in eclipse IDE by File -> New -> Android Project , fill all the required detail, Now a new project is created in project explorer.

 

 

2.

Now make a refference of facebook SDK (previously created) project to this project by Right Click on Project -> Properties -> android -> Click on Add button -> select your facebook project -> Click Apply.

 

refer facebook sdk project as library

 

File : AndroidManifest.xml

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidexample.facebook"
    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="com.androidexample.facebook.AndroidExampleFacebookActivity" >
            <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>

 

File : AndroidExampleFacebookActivity.java

 


package com.androidexample.facebook;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import org.json.JSONException;
import org.json.JSONObject;

@SuppressWarnings("deprecation")
public class AndroidExampleFacebookActivity extends Activity {

	// Facebook Application APP ID (Get it from faacebook app setting page)
	private static String APP_ID = "912301902217993"; 

	private AsyncFacebookRunner fbAsyncRunner;
	private SharedPreferences fbPrefs;
	
	// Create Object of Facebook Class
	private Facebook facebook = new Facebook(APP_ID);
	
	
	// Buttons
	Button fbLoginButton;
	Button fbMyProfileButton;
	Button fbFriendButton;
	Button fbPostToWallButton;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		fbLoginButton = (Button) findViewById(R.id.login_btn);
		fbMyProfileButton = (Button) findViewById(R.id.profile_btn);
		fbPostToWallButton = (Button) findViewById(R.id.wall_btn);
		fbFriendButton = (Button) findViewById(R.id.friend_btn);
		fbAsyncRunner = new AsyncFacebookRunner(facebook);

		//Login button Clicked
		fbLoginButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				
				facebookLogin();
				
			}
		});

		
       // My facebook Profile info
		fbMyProfileButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				getFacebookProfileInfo();
			}
		});

		// Post at Facebook Wall
		fbPostToWallButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				
				facebookWallPost();
				
			}
		});

		// Post at Facebook Wall
		fbFriendButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				
				getFacebookFriends();
				
			}
		});
	}

	// Function for login
	public void facebookLogin() {
		
        // Create shared preference to save login or not
		
		fbPrefs = getPreferences(MODE_PRIVATE);
		String access_token = fbPrefs.getString("access_token", null);
		
		// Get Expire value from shared preference
		long expires = fbPrefs.getLong("access_expires", 0);

		if (access_token != null) {
			// Get facebook access token to call facebook Graph api
			facebook.setAccessToken(access_token);
			
			fbLoginButton.setVisibility(View.INVISIBLE);
			
			// Make button visible
			fbMyProfileButton.setVisibility(View.VISIBLE);
            fbPostToWallButton.setVisibility(View.VISIBLE);
            fbFriendButton.setVisibility(View.VISIBLE);
		}

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

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

						@Override
						public void onCancel() {
							// Here work for facebook login page cancel event
						}

						@Override
						public void onComplete(Bundle values) {
							
							// update Shared Preferences values
							SharedPreferences.Editor editor = fbPrefs.edit();
							editor.putString("access_token",
									facebook.getAccessToken());
							editor.putLong("access_expires",
									facebook.getAccessExpires());
							editor.commit();

							// Make button invisible
							fbLoginButton.setVisibility(View.INVISIBLE);

							// Make button visible
							fbMyProfileButton.setVisibility(View.VISIBLE);
							fbPostToWallButton.setVisibility(View.VISIBLE);
							fbFriendButton.setVisibility(View.VISIBLE);
							
						}

						@Override
						public void onError(DialogError error) {
							// Here Work for handle error

						}

						@Override
						public void onFacebookError(FacebookError fberror) {
							// Here Work for handle Facebook errors

						}

					});
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		facebook.authorizeCallback(requestCode, resultCode, data);
	}


	// My Profile information 
	public void getFacebookProfileInfo() {
        
        // Make graph api call url like below line
        // https://graph.facebook.com/me?access_token=<your-api-token>&format=json

		fbAsyncRunner.request("me", new RequestListener() {
			@Override
			public void onComplete(String response, Object state) {
				Log.d("Profile", response);
				String json = response;
				try {
					// Got My Facebook Profile data in JSON format
					JSONObject profile = new JSONObject(json);
					
					// extract user name
					final String name = profile.getString("name");
					
					
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							Toast.makeText(getApplicationContext(), "My Name: " + name , 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) {
			}
		});
	}

	// My Freinds information 
	
    public void getFacebookFriends() {
        
         // Make graph api call url like below line
         // https://graph.facebook.com/me/friends?access_token=<your-api-token>&format=json

			  fbAsyncRunner.request("me/friends", new RequestListener() {
				@Override
				public void onComplete(String response, Object state) {
					
					Log.d("Number Of Freinds", response);
					
					String json = response;
					
					try {
						// Got My Facebook Freinds in JSON format
						JSONObject profile = new JSONObject(json);
						
						// extract user name
						final String total_count = profile.getString("summary");
						
						
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								Toast.makeText(getApplicationContext(), "Number Of Friends: " + total_count , 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) {
				}
			});
		}

	
	//Post to wall function
	public void facebookWallPost() {
		
		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() {
			}
		});

	}

}

If you have got this type error then see below image.

got_facebook_error

 

Share this: