Code2care : TechZone Apps & Tutorials

Integrating Facebook SDK version 3.5.2 with Android app Tutorial



Note :



31st August 2014 Update : Facebook SDK for Android v3.17.2 with major changes. So this tutorial is obsolete.

New tutorials for v3.17 : http://code2care.org/pages/integrating-android-facebook-sdk-v3.17.2-tutorial

Facebook developer's site has come up with the latest android SDK 3.6, so i have re written this blog and uploaded the code package on GitHub.

Link : Facebook SDK 3.6 integration tutorial




Facebook has a very well explained tutorial on how to integrate Facebook SDK with android app, but most of us face some or the other issues while doing so.

Here is a tutorial on how to share contents on facebook wall from your app through native Facebook application integration, the tutorial covers solutions to most of the issues that one may get stuck.

Prerequisites
  • You need the latest Facebook SDK for Android Facebook SDK
  • You need Java v1.6 or later.
  • You must have Eclipse Juno v4.2 or later with a default install and the Android SDK.
  • You need to have the Android 2.2 (API 8) components installed in order to use the Facebook SDK.


  • Installing Facebook App apk file on the Emulator.


    As Emulator does not have Play Store on it, you need to install the facebook.apk file using adb tool.

    If you want to test the SDK integration on your Android device, you don't need to follow below step, just make sure you have Facebook apk installed on your device.

  • Open AVD Manager (you may find it in eclispe under Window > Android Virtual Device Manager)

  • Create a new AVD (if you already have one, no need to create new)

  • Now Launch the AVD (Note : wait till the Emulator fully load)

  • Extract the Facebook SDK 3.5.2 file and locate the apk file. Note down the location (for me the location is C:\facebook-android-sdk-3.5.2\facebook-android-sdk-3.5.2\bin\FBAndroid-3.6.1.apk)

  • We need to locate the adb tool ( for me the location is H:\Program Files\adt-bundle-windows-x86_64-20130522\adt-bundle-windows-x86_64-20130522\sdk\platform-tools)

  • Open command prompt and go to location where adb tool is present.

  • Execute the following command.

  •  adb install C:\facebook-android-sdk-3.5.2\facebook-android-sdk-3.5.2\bin\FBAndroid-3.6.1.apk

    Note : It may take 15-20 minutes to get the apk installed on the Emulator (keep patience).
    Once this is done, you will see Facebook app icon on your AVD.


    Setting-up your Workspace.


    Important! : Your facebook SDK files and Workspace should be on the same drive or else you may face issues. So before starting just make sure that they are under the same drive (for me its H:/)
  • Open Workspace,

  • Right Click > Import Existing Projects into Workspace

  • Locate FacebookSDK files and Select Facebook SDK only (deselect all others)

  • Check the JDK version it Should be 1.6

  • Create a new Android Project, fill in the Application name,Project Name and Package Name,

  • I have added an fb icon under bin > res > drawable-hdpi and have set it as a ImageView in MainActivity.

  • Note : You need to register your App on facebook developers site to get an app_id
  • Add app-id to string.xml
  • Under AndroidManifest.xml > Application Tab > Application Nodes , Add Meta Data with,

  • Name : com.facebook.sdk.ApplicationId
    Value : @string/app_id
  • Add an Activity
  • Name : com.facebook.LoginActivity
    Label : @string/app_name
  • Add Internet and ACCESS NETWORK STATE Permission under : AndroidManifest.xml > Application Tab > Application Nodes > User Permissions

  • android.permission.INTERNET
    android.permission.ACCESS_NETWORK_STATE

    Here is the MainActivity.java file which contains the code to post a status on Facebook wall,
    I have added some more functions to the code that what is provided by Facebook developers tutorial,

    1. checkNetwork() : To Check if Internet Connection is available.
    2. checkFbInstalled() : To Check if Native Facebook app is installed on device.
    package com.code2care.thebuddhaquotes;
    
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    
    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.content.pm.PackageInfo;
    import android.content.pm.PackageManager;
    import android.content.pm.PackageManager.NameNotFoundException;
    import android.content.pm.Signature;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.os.Bundle;
    
    import android.util.Base64;
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.ImageView;
    import android.widget.Toast;
    
    import com.facebook.Session;
    import com.facebook.SessionState;
    import com.facebook.UiLifecycleHelper;
    import com.facebook.widget.FacebookDialog;
    
    public class MainActivity extends Activity {
    
    	String message = "Hello there!";
    	private UiLifecycleHelper uiHelper;
    
    	ImageView facebook;
    
    	private Session.StatusCallback callback = new Session.StatusCallback() {
    		@Override
    		public void call(Session session, SessionState state,
    				Exception exception) {
    			onSessionStateChange(session, state, exception);
    		}
    	};
    
    	private void onSessionStateChange(Session session, SessionState state,
    			Exception exception) {
    		if (state.isOpened()) {
    			// System.out.println("Logged in...");
    		} else if (state.isClosed()) {
    			// System.out.println("Logged out...");
    		}
    	}
    
    	@Override
    	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    		super.onActivityResult(requestCode, resultCode, data);
    
    		uiHelper.onActivityResult(requestCode, resultCode, data,
    				new FacebookDialog.Callback() {
    					@Override
    					public void onError(FacebookDialog.PendingCall pendingCall,
    							Exception error, Bundle data) {
    						Log.e("Activity",
    								String.format("Error: %s", error.toString()));
    					}
    
    					@Override
    					public void onComplete(
    							FacebookDialog.PendingCall pendingCall, Bundle data) {
    						Log.i("Activity", "Success!");
    					}
    				});
    	}
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    
    		uiHelper = new UiLifecycleHelper(this, callback);
    		uiHelper.onCreate(savedInstanceState);
    		
    		
    		//Code to get KeyHash value.
    		try {
    	        PackageInfo info = getPackageManager().getPackageInfo(
    	                "com.code2care.thebuddhaquotes", 
    	                PackageManager.GET_SIGNATURES);
    	        for (Signature signature : info.signatures) {
    	            MessageDigest md = MessageDigest.getInstance("SHA");
    	            md.update(signature.toByteArray());
    	            System.out.println("KeyHash : "+ Base64.encodeToString(md.digest(), Base64.DEFAULT));
    	            }
    	    } catch (NameNotFoundException e) {
    	    } catch (NoSuchAlgorithmException e) {
    	    }
    		
    
    		facebook = (ImageView) findViewById(R.id.fbIcon);
    
    		facebook.setOnClickListener(new OnClickListener() {
    
    			@Override
    			public void onClick(View v) {
    				facebook();
    
    			}
    		});
    	}
    
    	@Override
    	public boolean onCreateOptionsMenu(Menu menu) {
    		// Inflate the menu; this adds items to the action bar if it is present.
    		getMenuInflater().inflate(R.menu.main, menu);
    		return true;
    	}
    
    	@Override
    	protected void onDestroy() {
    		uiHelper.onDestroy();
    		super.onDestroy();
    	}
    
    
    	@Override
    	protected void onResume() {
    		super.onResume();
    		uiHelper.onResume();
    	}
    
    	@Override
    	protected void onSaveInstanceState(Bundle outState) {
    		super.onSaveInstanceState(outState);
    		uiHelper.onSaveInstanceState(outState);
    	}
    
    	@Override
    	public void onPause() {
    		super.onPause();
    		uiHelper.onPause();
    	}
    
    	public void facebook() {
    		if (!checkNetwork()) {
    			Toast.makeText(getApplicationContext(),
    					"No active internet connection ...", Toast.LENGTH_SHORT)
    					.show();
    			return;
    		}
    
    		if (!checkFbInstalled()) {
    			Toast.makeText(getApplicationContext(),
    					"Facebook app not installed!..", Toast.LENGTH_SHORT).show();
    			return;
    		}
    		Toast.makeText(getApplicationContext(), "Loading...",
    				Toast.LENGTH_SHORT).show();
    		if (FacebookDialog.canPresentShareDialog(this,
    				FacebookDialog.ShareDialogFeature.SHARE_DIALOG)) {
    
    			FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(
    					this).setName("The Buddha Quotes")
    					.setLink("http://code2care.org").setDescription(message)
    					.setPicture("http://code2care.org/buddha.jpg").build();
    			uiHelper.trackPendingDialogCall(shareDialog.present());
    
    		} else {
    			// System.out.println("Fail Success!");
    		}
    	}
    
    	private boolean checkNetwork() {
    		boolean wifiAvailable = false;
    		boolean mobileAvailable = false;
    
    		ConnectivityManager conManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    		NetworkInfo[] networkInfo = conManager.getAllNetworkInfo();
    		for (NetworkInfo netInfo : networkInfo) {
    			if (netInfo.getTypeName().equalsIgnoreCase("WIFI"))
    				if (netInfo.isConnected())
    					wifiAvailable = true;
    			if (netInfo.getTypeName().equalsIgnoreCase("MOBILE"))
    				if (netInfo.isConnected())
    					mobileAvailable = true;
    		}
    		return wifiAvailable || mobileAvailable;
    	}
    
    	public Boolean checkFbInstalled() {
    
    		PackageManager pm = getPackageManager();
    		boolean flag = false;
    		try {
    			pm.getPackageInfo("com.facebook.katana",
    					PackageManager.GET_ACTIVITIES);
    			flag = true;
    		} catch (PackageManager.NameNotFoundException e) {
    			flag = false;
    		}
    		return flag;
    	}
    
    }
    
  • Now if you run the program will get this error Jar mismatch! Fix your dependencies, to fix this issue you need to delete android-support-v4.jar under Your Project libs folder and place here the same file from FacebookSDK project's libs file.
  • Getting Keyhash



    This is the step where most of us get stuck. The quickest and easiest way to get keyhash is add the following code to onCreate function.
    try {
        PackageInfo info = getPackageManager().getPackageInfo(
        "com.code2care.thebuddhaquotes", 
        PackageManager.GET_SIGNATURES);
          for (Signature signature : info.signatures) {
           MessageDigest md = MessageDigest.getInstance("SHA");
           md.update(signature.toByteArray());
           System.out.println("KeyHash : "+ Base64.encodeToString(md.digest(),       Base64.DEFAULT));
            }
       } catch (NameNotFoundException e) {
     } catch (NoSuchAlgorithmException e) {
    } 
    Note : Remember to change the package name accordingly
    (for me its com.code2care.thebuddhaquotes)
    Once you run the app you will find the keyhash in LogCat,
    You need to add this keyhash to your facebook developer accounts App details page.


    Top




    Posts related to facebookSDK.


    1. FacebookSDK] Unable to resolve target android-8 (Android Facebook SDK error)

    2. Integrating Facebook SDK version 3.5.2 with Android app Tutorial

    3. Android Facebook SDK 3.6 Tutorial Integration With your App

    4. Facebook This Message Contains Blocked Content

    5. Integrating Android Facebook SDK v3.17.2 Tutorial

    6. Facebook App page error : You have specified an App Domain but have not specified a valid integration URL

    7. Facebook android SDK error while Linking the SDK project to your project (red cross against the package)

    8. java.lang.NoClassDefFoundError android.support.v4.content.LocalBroadcastManager Error


    Posts related to facebook.


    1. Facebook like box overlaps fixed div element while scrolling the page

    2. Facebook Error Sorry something went wrong

    3. Generate facebook android SDK keyhash using java code

    4. Integrating Android Facebook SDK v3.17.2 Tutorial

    5. java.lang.NoClassDefFoundError android.support.v4.content.LocalBroadcastManager Error

    6. Share Story Feeds on Facebook using URL

    7. Installing Facebook app on android Emulator using adb-tool, Windows and Mac

    8. Android Facebook SDK 3.6 Tutorial Integration With your App

    9. How to check if Facebook Application is installed on Android Device

    10. Facebook android SDK error while Linking the SDK project to your project (red cross against the package)

    11. FacebookSDK] Unable to resolve target android-8 (Android Facebook SDK error)

    12. Integrating Facebook SDK version 3.5.2 with Android app Tutorial

    13. Facebook App page error : You have specified an App Domain but have not specified a valid integration URL

    14. Can we move apps like WhatsApp, Facebook to external MicroSD card

    15. Facebook This Message Contains Blocked Content

    16. How to add line break in Facebook comment box

        more...

    Posts related to android.


    1. Share image and text Twitter using your Android Application Programatically

    2. The Android Virtual Device 'myEmulator' is currently running an emulator and cannot be deleted.

    3. Make Android View Scrollable both Horizontally and Vertically

    4. Can we move apps like WhatsApp, Facebook to external MicroSD card

    5. Parsing Data for android-21 failed unsupported major.minor version 51.0

    6. Android : Prevent App for rotation landscape or portrait

    7. ADT quit unexpectedly error on Mac OSX Android Eclipse SDK

    8. Android-Failed to install apk on device EOF Timeout Error

    9. How to change Android EditText Cursor Color

    10. JavaDocs for Android SDK Eclipse IDE

    11. Two Buttons next to each other in Android Layout

    12. Change Title text for Android Activity using java code

    13. How to add Newline to text in Android TextView

    14. Android : Unable to load VM from snapshot : Mac OS X Error

    15. INVALID FILE NAME: MUST CONTAIN ONLY [a-z0-9_.] Android Eclipse Error

    16. Hide Tittle bar and Navigation bar from android activity

    17. appcompat_v7 errors after updates to API level 21 Material Theme

    18. How to Copy Text to Android Clipboard Programatically ClipboardManager (Both Old and New SDK)

    19. [Solution] Running Android Lint has encountered a problem NullPointerException Error

    20. Remove Trailing zeros BigDecimal Java

        more...






    Popular tags
    android
    x 175
    eclipse
    x 29
    notepadplusplus
    x 20
    macosx
    x 14
    sharepoint
    x 14
    html
    x 14
    mac
    x 13
    androidstudio
    x 11




    1000+ C Programs     PHP Tutorial     JSON Tutorial     Swift Tutorial     India Pinocdes     About Us     Privacy Policy


    Code2care © 2012-17