How To Add Facebook Comment Widget In A Post




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 before you start. 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 How to implement Facebook Like Button, Share Link using Latest Android Facebook SDK, Share Image Using Latest Android Facebook SDK and Share Video Files using Custom Button. You can check out these tutorials, if you need.

Output

At the end of this tutorial, you will get output similar as below.

Tutorialwing - Android Facebook Comment Widget Output

Tutorialwing – Android Facebook Comment Widget Output

Source Code

1. Getting Started

In this tutorial, you will learn how to add facebook comment widget into 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 FacebookCommentsTutorial 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 your project. However, let me give brief explanation about what i have done till now to setup facebook sdk.

1.2.1 Add design-support library gradle into app/build.gradle.
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.1'
    testCompile 'junit:junit:4.12'

    // design support library
    compile 'com.android.support:design:24.2.1'
}
1.2.2 Add internet permission and meta data into AndroidManifest.xml file.

Add internet permission into AndroidManifest.xml file. Finally, AndroidManifest.xml file would look like below.

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.tutorialwing.facebookcommentstutorial"
          xmlns:android="http://schemas.android.com/apk/res/android">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <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.3 MainActivity Preview

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

package com.tutorialwing.facebookcommentstutorial;

import android.os.Bundle;
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>



2. Load the article to comment

At First, Load the article in which you want to add comment. Here, we are loading the article in MainActivity. So, open MainActivity.java and activity_main.xml file and add below code.
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
	android:id="@+id/main_content"
	xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:app="http://schemas.android.com/apk/res-auto"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:background="@android:color/white"
	android:fitsSystemWindows="true">

	<android.support.v7.widget.Toolbar
		android:id="@+id/toolbar"
		android:layout_width="match_parent"
		android:layout_height="?attr/actionBarSize"
		app:layout_collapseMode="pin"
		app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

	<WebView
		android:id="@+id/web_view"
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:layout_gravity="center_horizontal"
		app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

	<android.support.design.widget.FloatingActionButton
		android:id="@+id/fab"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_gravity="bottom|end"
		android:layout_margin="10dp"
		android:src="@drawable/ic_comment"/>

</android.support.design.widget.CoordinatorLayout>

MainActivity.java

package com.tutorialwing.facebookcommentstutorial;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

	String postUrl = "http://tutorialwing.com/android-facebook-integration-basic-setup/";

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

		setFloatingActionButton();
		loadPageContent();
	}

	private void setFloatingActionButton() {
		FloatingActionButton fb = (FloatingActionButton) findViewById(R.id.fab);
		fb.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, CommentActivity.class);
				intent.putExtra("url", postUrl);
				startActivity(intent);
			}
		});
	}

	private void loadPageContent() {
		WebView webView = (WebView) findViewById(R.id.web_view);
		if (webView != null) {
			webView.loadUrl(postUrl);
		}
	}
}

Here, we have loaded post in WebView. On Click of FloatingActionButton, CommentActivity activity will be shown that contains widget to post comment.

3. Start Implementing Android Facebook Comment widget To Comment On Any Post

By adding facebook comment widget, you let the user allow to comment on your post in website. Here, we are going to use facebook widget(created using html and javascript).

Facebook Comment Widget

"<!doctype html> " +
		"<html lang=\"en\">" +
		"<head></head>" +
		"<body> " +
		"<div id=\"fb-root\"></div>\n" +
		"<script>(function(d, s, id) {\n" +
		"  var js, fjs = d.getElementsByTagName(s)[0];\n" +
		"  if (d.getElementById(id)) return;\n" +
		"  js = d.createElement(s); js.id = id;\n" +
		"  js.src = \"//connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v2.8&appId=840985389316327\";\n" +
		"  fjs.parentNode.insertBefore(js, fjs);\n" +
		"}(document, 'script', 'facebook-jssdk'));</script>" +
		"<div class=\"fb-comments\" data-href=\"" + postUrl + "\" " +
		"data-numposts=\"" + NUMBER_OF_COMMENTS + "\" data-order-by=\"reverse_time\">" +
		"</div>" +
		"</body>" +
		"</html>";

We are also adding WebViewClient (that will receive various notifications and requests) and WebChromeClient(A handler for Chrome to handle JavaScript dialogs, favicons, titles, and the progress.).

Final CommentActivity code

package com.tutorialwing.facebookcommentstutorial;

import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.ViewGroup;
import android.webkit.ConsoleMessage;
import android.webkit.CookieManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

public class CommentActivity extends AppCompatActivity {

	private static final int NUMBER_OF_COMMENTS = 10;

	private String postUrl;

	private WebView commentsView;
	private WebView webViewPopup;

	private FrameLayout containerWebView;

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

		postUrl = getIntent().getStringExtra("url");

		commentsView = (WebView) findViewById(R.id.commentsView);
		containerWebView = (FrameLayout) findViewById(R.id.webViewContainer);

		loadComments();
	}

	private void loadComments() {
		if (commentsView == null)
			return;

		commentsView.setWebViewClient(new UriWebViewClient());
		commentsView.setWebChromeClient(new UriChromeClient());
		commentsView.setMinimumHeight(200);
		configureWebSettings(commentsView);

		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.setAcceptCookie(true);

		if (Build.VERSION.SDK_INT >= 21) {
			WebSettings settings = commentsView.getSettings();
			if (settings != null) {
				settings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
			}
			cookieManager.setAcceptThirdPartyCookies(commentsView, true);
		}

		// Get the Facebook Widget with post Url.
		String html = createFacebookCommentWidget();
		commentsView.loadDataWithBaseURL("http://tutorialwing.com", html, "text/html", "UTF-8", null);
	}

	private String createFacebookCommentWidget() {
		return "<!doctype html> " +
				"<html lang=\"en\">" +
				"<head></head>" +
				"<body> " +
				"<div id=\"fb-root\"></div>\n" +
				"<script>(function(d, s, id) {\n" +
				"  var js, fjs = d.getElementsByTagName(s)[0];\n" +
				"  if (d.getElementById(id)) return;\n" +
				"  js = d.createElement(s); js.id = id;\n" +
				"  js.src = \"//connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v2.8&appId=840985389316327\";\n" +
				"  fjs.parentNode.insertBefore(js, fjs);\n" +
				"}(document, 'script', 'facebook-jssdk'));</script>" +
				"<div class=\"fb-comments\" data-href=\"" + postUrl + "\" " +
				"data-numposts=\"" + NUMBER_OF_COMMENTS + "\" data-order-by=\"reverse_time\">" +
				"</div>" +
				"</body>" +
				"</html>";
	}

	private void configureWebSettings(WebView webView) {
		if (webView != null) {
			WebSettings settings = webView.getSettings();
			if (settings != null) {
				settings.setJavaScriptEnabled(true);
				settings.setDomStorageEnabled(true);
				settings.setSupportZoom(false);
				settings.setBuiltInZoomControls(false);
				settings.setSupportMultipleWindows(true);
				settings.setAppCacheEnabled(true);
				settings.setJavaScriptCanOpenWindowsAutomatically(true);
			}
		}
	}

	private WebView createWebView(WebChromeClient webChromeClient, WebViewClient webViewClient) {
		WebView newWebView = new WebView(getApplicationContext());
		newWebView.setVerticalScrollBarEnabled(false);
		newWebView.setHorizontalScrollBarEnabled(false);
		newWebView.setWebViewClient(webViewClient);
		newWebView.setWebChromeClient(webChromeClient);
		newWebView.setLayoutParams(new FrameLayout.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
		return newWebView;
	}

	private class UriWebViewClient extends WebViewClient {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			String host = Uri.parse(url).getHost();
			return !host.equals("m.facebook.com");
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);

			boolean isRemovePopup = url.contains("/plugins/close_popup.php?reload");
			if (isRemovePopup) {
				final Handler handler = new Handler();
				handler.postDelayed(new Runnable() {
					@Override
					public void run() {
						// Code to load comments and remove dynamically created webView.
						containerWebView.removeView(webViewPopup);
						loadComments();
					}
				}, 600);
			}
		}

		@Override
		public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
		}
	}

	class UriChromeClient extends WebChromeClient {

		@Override
		public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {

			webViewPopup = createWebView(this, new WebViewClient());
			configureWebSettings(webViewPopup);
			containerWebView.addView(webViewPopup);

			WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
			transport.setWebView(webViewPopup);
			resultMsg.sendToTarget();
			return true;
		}

		@Override
		public boolean onConsoleMessage(ConsoleMessage cm) {
			return true;
		}

		@Override
		public void onCloseWindow(WebView window) {
		}
	}
}
activity_comment.xml

This file contains container for comment widget.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
	android:id="@+id/activity_comment"
	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: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.tutorialwing.facebookcommentstutorial.CommentActivity">

	<FrameLayout
		android:id="@+id/webViewContainer"
		xmlns:android="http://schemas.android.com/apk/res/android"
		android:layout_width="match_parent"
		android:layout_height="match_parent">

		<WebView
			android:id="@+id/commentsView"
			android:layout_width="match_parent"
			android:layout_height="match_parent"
			android:layout_gravity="center_horizontal"/>

	</FrameLayout>

</RelativeLayout>

You can change the post by passing a different url from MainActivity to CommentActivity.

That’s all for Adding Facebook Comment widget in android application.




Output

If you run the app, you will see a floating action button. Clicking on this button will show an activity. This activity contains all the comments in the post. It also includes an ui through which you can comment on the post. Finally, you will get output as shown above.

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 login, share content for example images, audio files, video files or any media files etc. We can also use facebook comment widget to comment on any post. 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.