Search code examples
androidandroid-activitywebviewandroid-fragmentactivityfacebook-sdk-4.0

How to make facebook comment activity for multiple URLs in webview?


Im trying to build Webview app where user can post comment on webpages using facebook comment activity. If URL keeps changing in webview how to get URL to FbCommentActivity.java. Please note that Facebook Comment Plugin is already installed in all webpages.

I tried using "TAG_LINK" in my webview fragment which stores app links when bookmark button is pressed but still its not working. Also note if i use mWebViewComments.loadDataWithBaseURL("http://www.example.com") comments are loading since comments is used for different pages defining http BaseURL method fails. For example :i have two web pages http://example/page1, http://example/page2. How to make commentactivity when there is multiple web pages. Also i tried webview.getUrl() method Ex: postUrl = webview.getUrl(); but app is crashing when i click comment fab button. Kindly share your valuable inputs. I'm newbie in android please help me out.

FbCommentsActivity.java

 package seacoders.abhilash.bogguru;


 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.support.v7.widget.Toolbar;
 import android.text.TextUtils;
 import android.util.Log;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.view.View;
 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;
 import android.widget.ProgressBar;
 import android.widget.Toast;
 import seacoders.abhilash.bogguru.HomeFragment;

 public class FbCommentsActivity extends AppCompatActivity {
  private static String TAG = FbCommentsActivity.class.getSimpleName();
  private WebView mWebViewComments;
  private FrameLayout mContainer;
  private ProgressBar progressBar;
  boolean isLoading;
  private WebView mWebviewPop;
  private String postUrl;
  //    public String webUrl = getIntent().getExtras().getString("webUrl");
  // error is coming from here, according the the error log.

  // the default number of comments should be visible
  // on page load.
  private static final int NUMBER_OF_COMMENTS = 8;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_fb_comments);
   Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
   setSupportActionBar(toolbar);
   getSupportActionBar().setDisplayHomeAsUpEnabled(true);

   mWebViewComments = (WebView) findViewById(R.id.commentsView);
   mContainer = (FrameLayout) findViewById(R.id.webview_frame);
   progressBar = (ProgressBar) findViewById(R.id.progressBar);
   progressBar.setVisibility(View.VISIBLE);

   postUrl = getIntent().getStringExtra("TAG_LINK");
   // finish the activity in case of empty url
   if (TextUtils.isEmpty(postUrl)) {
    Toast.makeText(getApplicationContext(), "The web url shouldn't be empty", Toast.LENGTH_LONG).show();
    finish();
    return;
   }

   setLoading(true);
   loadComments();
  }

  private void loadComments() {
   mWebViewComments.setWebViewClient(new UriWebViewClient());
   mWebViewComments.setWebChromeClient(new UriChromeClient());
   mWebViewComments.getSettings().setJavaScriptEnabled(true);
   mWebViewComments.getSettings().setAppCacheEnabled(true);
   mWebViewComments.getSettings().setDomStorageEnabled(true);
   mWebViewComments.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
   mWebViewComments.getSettings().setSupportMultipleWindows(true);
   mWebViewComments.getSettings().setSupportZoom(false);
   mWebViewComments.getSettings().setBuiltInZoomControls(false);
   CookieManager.getInstance().setAcceptCookie(true);
   if (Build.VERSION.SDK_INT >= 21) {
    mWebViewComments.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    CookieManager.getInstance().setAcceptThirdPartyCookies(mWebViewComments, true);
   }

   // facebook comment widget including the article url
   String html = "<!doctype html> <html lang=\"en\"> <head></head> <body> " +
    "<div id=\"fb-root\"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = \"//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.6\"; fjs.parentNode.insertBefore(js, fjs); }(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>";

   mWebViewComments.loadDataWithBaseURL(postUrl, html, "text/html", "UTF-8", null);
   mWebViewComments.setMinimumHeight(200);
  }

  private void setLoading(boolean isLoading) {
   this.isLoading = isLoading;

   if (isLoading)
    progressBar.setVisibility(View.VISIBLE);
   else
    progressBar.setVisibility(View.GONE);

   invalidateOptionsMenu();
  }

  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);
    String host = Uri.parse(url).getHost();
    setLoading(false);
    if (url.contains("/plugins/close_popup.php?reload")) {
     final Handler handler = new Handler();
     handler.postDelayed(new Runnable() {
      @Override
      public void run() {
       //Do something after 100ms
       mContainer.removeView(mWebviewPop);
       loadComments();
      }
     }, 600);
    }
   }

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

  class UriChromeClient extends WebChromeClient {

   @Override
   public boolean onCreateWindow(WebView view, boolean isDialog,
    boolean isUserGesture, Message resultMsg) {
    mWebviewPop = new WebView(getApplicationContext());
    mWebviewPop.setVerticalScrollBarEnabled(false);
    mWebviewPop.setHorizontalScrollBarEnabled(false);
    mWebviewPop.setWebViewClient(new UriWebViewClient());
    mWebviewPop.setWebChromeClient(this);
    mWebviewPop.getSettings().setJavaScriptEnabled(true);
    mWebviewPop.getSettings().setDomStorageEnabled(true);
    mWebviewPop.getSettings().setSupportZoom(false);
    mWebviewPop.getSettings().setBuiltInZoomControls(false);
    mWebviewPop.getSettings().setSupportMultipleWindows(true);
    mWebviewPop.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
     ViewGroup.LayoutParams.MATCH_PARENT));
    mContainer.addView(mWebviewPop);
    WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
    transport.setWebView(mWebviewPop);
    resultMsg.sendToTarget();

    return true;
   }

   @Override
   public boolean onConsoleMessage(ConsoleMessage cm) {
    Log.i(TAG, "onConsoleMessage: " + cm.message());
    return true;
   }

   @Override
   public void onCloseWindow(WebView window) {}
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
   if (!isLoading) {
    getMenuInflater().inflate(R.menu.fb_comments, menu);
   }

   return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
   if (item.getItemId() == android.R.id.home) {
    onBackPressed();
    return true;
   }

   if (item.getItemId() == R.id.action_refresh) {
    mWebViewComments.reload();
   }

   return super.onOptionsItemSelected(item);
  }
 }

HomeFragment.java

package seacoders.abhilash.bogguru;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.net.URI;
import java.util.ArrayList;
import seacoders.abhilash.bogguru.FavFragment;
import static seacoders.abhilash.bogguru.FavFragment.TAG_LINK;

public class HomeFragment extends Fragment {
 static WebView wv, cv = null;
 TextView txt;
 ProgressBar pbar;
 FloatingActionButton cmt, fav;
 Context mcontext;



 public static final String PREFERENCES = "PREFERENCES_NAME";
 String WEB_LINKS = "links";
 String WEB_TITLE = "title";
 //String PageURL = getActivity().getIntent().getStringExtra("url");
 public String current_page_url;
 public static final String TITLE = "Home";


 public static HomeFragment newInstance() {

  return new HomeFragment();
 }

 @Nullable
 @Override
 public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
  //return inflater.inflate(R.layout.fragment_home, container, false);
  setHasOptionsMenu(true);
  final View v = inflater.inflate(R.layout.fragment_home, container, false);
  wv = (WebView) v.findViewById(R.id.webview);
  wv.loadUrl("http://bogguru.we.bs/bogguru-android-mobile-application/webapp/index.html");
  current_page_url = "http://bogguru.we.bs/bogguru-android-mobile-application/webapp/";
  SharedPreferences sharedPreferences = getActivity().getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
  String links = sharedPreferences.getString(WEB_LINKS, null);
  if (links != null) {
   Gson gson = new Gson();
   ArrayList < String > linkList = gson.fromJson(links, new TypeToken < ArrayList < String >> () {}.getType());
  }

  if (getActivity().getIntent().getExtras() != null) {
   TAG_LINK = getActivity().getIntent().getStringExtra("url");
  }
  //facebook comment
  cmt = (FloatingActionButton) v.findViewById(R.id.fabcmt);
  cmt.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    // launching facebook comments activity
    Intent intent = new Intent(getActivity(), FbCommentsActivity.class);

    //fb comment passing the article url
    intent.putExtra("TAG_LINK", "http://www.bogguru.we.bs/");
    startActivity(intent);
   }
  });
  // end of fb comment
 }
}

activity_fb_comment.xml

<
android.support.design.widget.CoordinatorLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: app = "http://schemas.android.com/apk/res-auto"
xmlns: tools = "http://schemas.android.com/tools"
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: fitsSystemWindows = "true"
tools: context = ".FbCommentsActivity" >

 <
 android.support.design.widget.AppBarLayout
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: theme = "@style/AppTheme.AppBarOverlay" >

 <
 android.support.v7.widget.Toolbar
android: id = "@+id/toolbar"
android: layout_width = "match_parent"
android: layout_height = "?attr/actionBarSize"
android: background = "?attr/colorPrimary"
app: popupTheme = "@style/AppTheme.PopupOverlay" / >

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

 <
 LinearLayout
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: orientation = "vertical"
app: layout_behavior = "@string/appbar_scrolling_view_behavior" >

 <
 FrameLayout xmlns: android = "http://schemas.android.com/apk/res/android"
android: id = "@+id/webview_frame"
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" / >

 <
 ProgressBar
android: id = "@+id/progressBar"
android: layout_width = "30dp"
android: layout_height = "30dp"
android: layout_alignParentBottom = "true"
android: layout_centerHorizontal = "true"
android: layout_gravity = "center"
android: layout_marginBottom = "10dp"
android: indeterminateTint = "@color/colorPrimary"
android: indeterminateTintMode = "src_atop" / >

 <
 /FrameLayout> <
 /LinearLayout>

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

Solution

  • BINGO!!! finally this worked for me. I added following lines in FbCommentsActivity.java

     WebView wv = (WebView) findViewById(R.id.webview);// my HomeFragment WEBVIEW
        postUrl = HomeFragment.wv.getUrl(); //get Url from Homefragment webview