Implement Facebook Like Button Using Android Facebook SDK




Hello Readers! Welcome to Android facebook integration series. If you are trying to advertise your app, integrating social media into your application is one of the best way to do it. Number of people using social media like facebook, twitter, LinkedIn etc. are increasing day by day. So, their importance as marketing tools or connecting your business with the people can not be underestimated. Moreover, It’s free. You don’t need to pay a single penny for this.
Here, we will talk about facebook integration in android application. Now, it’s very easy to integrate facebook into android applications using android facebook SDK. You can easily share post, media, videos, link etc. using just a few lines of code. Before starting this tutorial, I strongly recommend to go through How to basic setup for facebook SDK post. This tutorial talks about how to create facebook app, do basic setup etc. These are necessary steps to share any media files using android facebook SDK. However, we have also written post on Share Link using Latest Android Facebook SDK, Share Image Using Latest Android Facebook SDK, Share Video Files using Custom Button and Share Media Files using Android Facebook SDK. You can check out these tutorials, if you need.

Output

Tutorialwing - Android Facebook Like tutorial Output

Tutorialwing – Android Facebook Like tutorial Output

Source Code

1. Getting Started

In this tutorial, we are going to implement Android facebook like button in your android application.

1.1 Creating a new project

Follow steps written below to create a new project.
a. Goto File –> New –> New Project. Then, Write application name as AndroidFacebookLikeTutorial and click next.
b. Select Minimum SDK 15 or more –> click next –> Select Empty Activity –> click next –> click finish.
If you have followed above process correctly, you will get a newly created project successfully.

1.2. Basic setup for Android Facebook SDK

You need to do some setup to use facebook sdk into your application. I have already discussed about it into this tutorial. Please have a look at this post and integrate facebook sdk into this project. However, let me give brief explanation about what i have done till now to setup facebook sdk into my application.

1.2.1 Add facebook-sdk gradle into app/build.gradle.

repositories {

    mavenCentral()

}


dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])

    testCompile 'junit:junit:4.12'

    compile 'com.android.support:appcompat-v7:24.2.0'


    compile 'com.facebook.android:facebook-android-sdk:[4,5)'

    compile 'com.android.support:support-v4:24.2.0'

}
1.2.2 Add facebook ID string into strings.xml file
<string name="facebook_app_id">YOUR FACEBOOK APP ID</string>
1.2.3 Add internet permission and meta data into AndroidManifest.xml file.

Finally, AndroidManifest.xml file would look like below.

<?xml version="1.0" encoding="utf-8"?>

<manifest package="tutorialwing.com.androidfacebookliketutorial"
          xmlns:android="http://schemas.android.com/apk/res/android">


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


    <application

        android:name=".MyApplication"

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:supportsRtl="true"

        android:theme="@style/AppTheme">


        <meta-data

            android:name="com.facebook.sdk.ApplicationId"

            android:value="@string/facebook_app_id"/>


        <activity android:name=".MainActivity">

            <intent-filter>

                <action android:name="android.intent.action.MAIN"/>


                <category android:name="android.intent.category.LAUNCHER"/>

            </intent-filter>

        </activity>


    </application>


</manifest>
1.2.4 Create MyApplication class

Create a class named MyApplication and extend it with Application class. Then, write code to print KeyHash in it.
Note: You don’t need this class if you don’t want to print keyHash.
MyApplication.java class

package tutorialwing.com.androidfacebookliketutorial;
import android.app.Application;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.util.Base64;
import android.util.Log;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MyApplication extends Application {

	@Override
	public void onCreate() {
		super.onCreate();
		printHashKey();
	}

	/**
	 * Method that prints hash key.
	 */
	public void printHashKey() {
		try {
			PackageInfo info = getPackageManager().getPackageInfo(
					"tutorialwing.com.androidfacebookliketutorial",
					PackageManager.GET_SIGNATURES);

			for (Signature signature : info.signatures) {
				MessageDigest md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
				Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
			}
		} catch (PackageManager.NameNotFoundException e) {
		} catch (NoSuchAlgorithmException e) {
		}
	}
}

Don’t forget to add android:name=”.MyApplication” for application in AndroidManifest.xml.

<application
      android:name=".MyApplication"
      -------->
</application>
1.2.5 MainActivity Preview

You have MainActivity.java and activity_main.xml file. At this point of time, It would look like below.
MainActivity.java

package tutorialwing.com.androidfacebookliketutorial;

import android.os.Bundle;

import android.support.v4.app.FragmentTransaction;

import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

	@Override

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);

	}

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin">


</RelativeLayout>



1.3 Start Implementing Android Facebook like View using latest Android Facebook SDK

Now, Everything is setup. So, we will see how to integrate android facebook like button into android application in following steps.
a. Create a fragment LikeFragment.java and it’s layout fragment_like.java. Write code to show like button and implement it’s functionality.
b. Use this fragment in MainActivity.java and show final output.

Let’s start with first step.

1.3.1 Create Fragment and implement android facebook like button into it

Create a fragment (named LikeFragment.java) and an xml file (named fragment_like.xml).

We use LikeView widget, provided by Facebook SDK, to implement like functionality into our application.

<com.facebook.share.widget.LikeView

    android:id="@+id/likeView"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"/>
1.3.1.1 Add LikeView widget into xml file

Open fragment_like.xml file and add LikeView widget into this file.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

              android:layout_width="match_parent"

              android:layout_height="match_parent"

              android:orientation="vertical">


    <com.facebook.share.widget.LikeView

        android:id="@+id/likeView"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"/>


</LinearLayout>
Write code to Setup LikeView into Java file

Open LikeFragment.java file and do following steps to customize LikeView button.

a. Initialise facebook sdk
// Initialize facebook SDK.
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
b. Set up CallbackManager

Create an instance of callbackManager to handle login responses. Call callbackManager.onActivityResult(requestCode, resultCode, data), in onActivityResult method, to pass loginResult to LoginManager via callBackManager.

@Override
public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
        //Code to perform other actions....
	// Create a callbackManager to handle the login responses.
	callbackManager = CallbackManager.Factory.create();
}

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

	// Call callbackManager.onActivityResult to pass login result to the LoginManager via callbackManager.
	callbackManager.onActivityResult(requestCode, resultCode, data);
}
c. Setup LikeButton

Write below code to customise LikeView Button inside setLikeButton(view) method and call this method inside onViewCreated( … ) method.

LikeView likeView = (LikeView) view.findViewById(R.id.likeView);

likeView.setLikeViewStyle(LikeView.Style.STANDARD);

likeView.setFragment(this);

likeView.setAuxiliaryViewPosition(LikeView.AuxiliaryViewPosition.INLINE);


String pageUrlToLike = "https://www.facebook.com/FacebookDevelopers";

likeView.setObjectIdAndType(pageUrlToLike, LikeView.ObjectType.PAGE);
Final LikeFragment.java class code
package tutorialwing.com.androidfacebookliketutorial;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.facebook.CallbackManager;
import com.facebook.FacebookSdk;
import com.facebook.share.widget.LikeView;

public class LikeFragment extends Fragment {

	private CallbackManager callbackManager;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Initialize facebook SDK.
		FacebookSdk.sdkInitialize(getActivity().getApplicationContext());

		// Create a callbackManager to handle the login responses.
		callbackManager = CallbackManager.Factory.create();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_like, container, false);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		setLikeButton(view);
	}

	private void setLikeButton(View view) {
		LikeView likeView = (LikeView) view.findViewById(R.id.likeView);
		likeView.setLikeViewStyle(LikeView.Style.STANDARD);
		likeView.setFragment(this);
		likeView.setAuxiliaryViewPosition(LikeView.AuxiliaryViewPosition.INLINE);

		String pageUrlToLike = "https://www.facebook.com/FacebookDevelopers";
		likeView.setObjectIdAndType(pageUrlToLike, LikeView.ObjectType.PAGE);
	}

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

		// Call callbackManager.onActivityResult to pass login result to the LoginManager via callbackManager.
		callbackManager.onActivityResult(requestCode, resultCode, data);
	}
}

Some key points used to setup like button: –
(i) likeView.setLikeViewStyle method: Sets the facebook style for this likeView.
(ii) likeView.setFragment method: Sets the parent Fragment which is hosting this LikeView. This allows the LikeView to be embedded inside a Fragment, and will allow the fragment to receive the onActivityResult.onActivityResult(int, int, android.content.Intent) call rather than the Activity, upon completion of Likes from this view.
(iii) likeView.setAuxiliaryViewPosition method: Sets the facebook:auxiliary_view_position for this LikeView.
(iv) likeView.setObjectIdAndType method: Sets the associated object ID for this LikeView. Pass url of the object(page, post etc.) and it’s type as parameter of this method.

Till this point, we are done with customising and setup of LikeView button. Now, we will use it MainActivity.java class.

1.3.2 Use LikeFragment in MainActivity.java and show output

Now, we are done with LikeView Customisation. Also, we have used this LikeView into LikeFragment. Now, We will ad this fragemnt into MainActivity to show final output. Finally, our activity_main.xml and MainActivity.java file would look like below.

activity_main.xml code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <LinearLayout
        android:id="@+id/facebook_like_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_centerInParent="true">
    </LinearLayout>
</RelativeLayout>

MainActivity.java code

package tutorialwing.com.androidfacebookliketutorial;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		addLikeFragment();
	}

	private void addLikeFragment() {
		LikeFragment likeFragment = new LikeFragment();
		FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
		fragmentTransaction.add(R.id.facebook_like_button, likeFragment);
		fragmentTransaction.commit();
	}
}



Output

If you run the app, you will see the output as shown above.

Important things to keep in mind

For Now, LikeView only works with administrator of the facebook app. However, If you want LikeView to work for others also ( or you want your app to be liked by others) you need to submit your app to facebook team. Only after successful verification, Others will be able to like your app( or page). To know How to submit your app, please go to this tutorials.

If you have already successfully submitted the app, then, LikeView will work for everyone. If not, It will work only after it is successfully verified by Facebook team.

Note: If you face any difficulty in this process, you can download the source code from above link.

Conclusion

Android Facebook SDK is easily understandable and very useful when we want to promote our business via social media. We can use Android Facebook SDK in our android application to like, login, share content for example images, audio files, video files or any media files etc. We have discussed each and everything in a separate post. You can check out these tutorials as well. Hope this tutorial helped you.

Support Us

If you have any suggestion about this post, please comment below. We are looking for someone who helps use to make our tutorial better. Also, If you want tutorials on any topic, you can mail us at tutorialwing@gmail.com. We will try to cover the topic as soon as possible. Connect with us on Facebook, Google+, Twitter and Youtube for more updates.

  • Ak

    Hello,
    I just implement the same code, the total like showing fine.
    But Whenever I tap on Like button for like page, the blank screen comes and app navigate to MainActivity Activity.

    • Did you check the logcat? What messages are you getting in it?