How to post status update or share link in Facebook from Android Application?

In this post, I am going to discuss about integrating Facebook share dialog in Android applications using Facebook SDK.

What is Facebook SDK?

Facebook provides SDK for Android to build Android applications to increase the engagement with it’s World’s number one Social Networking platform. To know more about Facebook SDK, please follow this link.

What are we going to develop?

The application which we are going to develop will have two buttons. We can post status update by clicking Button one and we can share link in Facebook using Button two. Facebook share dialog will be opened on clicking these buttons to perform aforementioned activities.

You can download source code from here if you don’t want to create Application from scratch, otherwise please proceed with below listings.

Prerequisites

Facebook SDK must be configured in your Eclipse IDE, please take help from this post – Getting Started with the Facebook SDK for Android to setup Facebook SDK.

Let us start with creating Android application.

Step 1: Create Android Application Project

  • Create new android project [File >> New >> Android Application Project] with project name FBShareActivity
  • Enter the package name and activity name you have entered in Facebook developer console while creating Facebook Application
  • Choose Minimum Required SDK, Target SDK and Compile with (Choose latest SDKs to make sure Facebook SDK will work without any issues). Confused on choosing these options? Take a look at Minimum Required SDK – Target SDK – Compile With post.
  • Click Next button and finally click ‘Finish’ to create project

Step 2: Add Facebook SDK as dependency project

Right click on the project you created >> Choose Properties >> Choose Android Tab >> Go to lower part of the dialog >> Click on Add button >> Select FacebookSDK Project.

Troubleshooting Tips:

  1. You should configure FacebookSDK in your workspace, that means import FacebookSDK library project into your workspace before your try to add it as dependency project.
  2. FacebookSDK library project and the Android application you just created should be under same Workspace.

Step 3: Design screen

Open activity_main.xml and replace it with below code.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_gradient"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.prgguru.example.MainActivity" >

    <Button
        android:id="@+id/postStatusUpdateButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:background="@drawable/bg_button_rounded"
        android:onClick="postStatusUpdate"
        android:text="Post Status Update"
        android:textColor="@color/white" />

    <Button
        android:id="@+id/shareButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:background="@drawable/bg_button_rounded"
        android:onClick="shareTutorialonFB"
        android:text="Share this tutorial on FB"
        android:textColor="@color/white" />

</LinearLayout>

Step 4: MainActivity.java – Main Class

Open MainActivity.java and replace it with below code.

Each line of code is commented well, if you still have any doubt or question discuss it.

package com.prgguru.example;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.app.Activity;
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.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.facebook.UiLifecycleHelper;
import com.facebook.widget.FacebookDialog;

public class MainActivity extends Activity {
	// Create, automatically open (if applicable), save, and restore the 
	// Active Session in a way that is similar to Android UI lifecycles. 
	private UiLifecycleHelper uiHelper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// To maintain FB Login session
		uiHelper = new UiLifecycleHelper(this, null);
		uiHelper.onCreate(savedInstanceState);
	}
	
		
	// When Post Status Update button is clicked
	public void postStatusUpdate(View v){
		// Pass null as parameter for setLink method to post status update
		FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(this)
        .setLink(null)
        .build();
		uiHelper.trackPendingDialogCall(shareDialog.present()); 
	}
	
	// When Share this tutorial on FB button is clicked
	public void shareTutorialonFB(View v){
		FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(this)
        .setLink("http://programmerguru.com/android-tutorial/getting-started-with-the-facebook-sdk-for-android/")
        .build();
		uiHelper.trackPendingDialogCall(shareDialog.present());
	}
	// After Facebook Dialog is closed
	@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) {
						Toast.makeText(getApplicationContext(), "Error OccurednMost Common Errors:n1. Device not connected to Internetn2.Faceboook APP Id is not changed in Strings.xml", Toast.LENGTH_LONG).show();
					}

					@Override
					public void onComplete(
							FacebookDialog.PendingCall pendingCall, Bundle data) {						
						Toast.makeText(getApplicationContext(),"Done!!",Toast.LENGTH_SHORT).show();
					}
				});
	}

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

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}
}

Step 5: Add the Facebook app ID into your project

Add your Facebook app ID into your project, open up the strings.xml file in the res/values folder of your project and add below value:

<string name="app_id">YOUR_FACEBOOK_APP_ID</string>

Step 6: Add Meta Data to application tag in AndroidManifest

As shown below, add a ‘Meta Data’ item called com.facebook.sdk.ApplicationId, with a value of the app_id string you just configured:

<meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/app_id" />

Step 7: Add permission in AndroidManifest.xml

Add Internet permission in AndroidManifest:

 <uses-permission android:name="android.permission.INTERNET" />

[pglinkadssmall1]

Here is the complete AndroidManifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.prgguru.example"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/app_id" />

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Demo

That’s all. It’s time to test our code.

Run the application using emulator or device by right clicking on the project >> Run as >> Android applicaiton >> Choose emulator or device.


Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project (How to import android project in eclipse).

Download Source Code

*apk in Android  is the installation file similar to exe in windows.

[pglinkadssmall]

If you feel this article is helpful and interesting please spread a word about it to your friends and colleagues by sharing the article in Facebook or Twitter.

Share

You are always welcome to provide your comments and feedback from comment box.

[pgwriteforus]

[pgfeedback]

Related Articles

Author: Udhay

Share This Post On
468 ad
  • Vishnu Sharma

    if user does not have facebook app then???????????????

  • App will stop working. It is better to check if facebook app is installed already in Android device.

Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest

Shares