Friday, 2 August 2013

Facebook Integration with Android App

Hi Guys!

Today I going to share about the Facebook Integration with Android App.
The Facebook SDK for Android is the easiest way to integrate your Android app with Facebook's platform. The SDK provides support for Login with Facebook authentication, reading and writing to Facebook APIs and support for UI elements such as pickers and dialogs.

What I am going to implement watch in video.



The First thing is Download and extract the SDK ZIP file. The resulting folder, facebook-android-sdk-3.0.2, contains the SDK itself. We need to add this sdk library with our new android app project.

Now the second thing is need to get the SHA1 (Hash Key). For this we need to download the openssl and install in our system and configure with the system environment variable. Here is the link to download the setup OpenSsl. 
And set the path like that C:\Program Files (x86)\GnuWin32\bin (this is default directory to install in your system).
In the next step we have to create a folder inside the C drive name "Android" and copy the debug.keystore (default directory in my system is "C:\Users\sunil\.android") and paste inside thie Android folder.

Now the time is to generate the sha1 key by using the keystore file so use this command
C:\>keytool -exportcert -alias androiddebugkey -keystore "C:\Android\debug.keystore" | openssl sha1 -binary | openssl base64



 Once run this command then it asking about password then give password "android". Then it will generate the app id.

Now need to use this app id with your Facebook account. So logged your Facebook Account and click on developer tab and click on Apps tab.

 
You need to registered as a developer and save your SHA1 key here.


In the next step we need to create the new app then go to dashboard Apps tab and create new app.

After that it show the app id and secret app id


So you can use this APP ID  in your android project.

Lets create the the android project name "First Android" and add the facebook sdk as a library.



Lets start the coding now.


activity_main.xml


    
    
    

MainActivity.java

package com.sunil;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

public class MainActivity extends Activity {

 // Your Facebook APP ID
 private static String APP_ID = "Your APP_ID"; // Replace with your App ID

 // Instance of Facebook Class
 private Facebook facebook = new Facebook(APP_ID);
 private AsyncFacebookRunner mAsyncRunner;
 String FILENAME = "AndroidSSO_data";
 private SharedPreferences mPrefs;

 // Buttons
 Button btnFbLogin;
 Button btnFbGetProfile;
 Button btnPostToWall;
 Button btnShowAccessTokens;

 @SuppressWarnings("deprecation")
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  btnFbLogin = (Button) findViewById(R.id.btn_fblogin);
  btnFbGetProfile = (Button) findViewById(R.id.btn_get_profile);
  btnPostToWall = (Button) findViewById(R.id.btn_fb_post_to_wall);
  btnShowAccessTokens = (Button) findViewById(R.id.btn_show_access_tokens);
  mAsyncRunner = new AsyncFacebookRunner(facebook);

  /**
   * Login button Click event
   * */
  btnFbLogin.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View v) {
    Log.d("Image Button", "button Clicked");
    loginToFacebook();
   }
  });

  /**
   * Getting facebook Profile info
   * */
  btnFbGetProfile.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View v) {
    getProfileInformation();
   }
  });

  /**
   * Posting to Facebook Wall
   * */
  btnPostToWall.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View v) {
    postToWall();
   }
  });

  /**
   * Showing Access Tokens
   * */
  btnShowAccessTokens.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View v) {
    showAccessTokens();
   }
  });

 }

 /**
  * Function to login into facebook
  * */
 @SuppressWarnings("deprecation")
 public void loginToFacebook() {

  mPrefs = getPreferences(MODE_PRIVATE);
  String access_token = mPrefs.getString("access_token", null);
  long expires = mPrefs.getLong("access_expires", 0);

  if (access_token != null) {
   facebook.setAccessToken(access_token);
   
   btnFbLogin.setVisibility(View.INVISIBLE);
   
   // Making get profile button visible
   btnFbGetProfile.setVisibility(View.VISIBLE);

   // Making post to wall visible
   btnPostToWall.setVisibility(View.VISIBLE);

   // Making show access tokens button visible
   btnShowAccessTokens.setVisibility(View.VISIBLE);

   Log.d("FB Sessions", "" + facebook.isSessionValid());
  }

  if (expires != 0) {
   facebook.setAccessExpires(expires);
  }

  if (!facebook.isSessionValid()) {
   facebook.authorize(this,
     new String[] { "email", "publish_stream" },
     new DialogListener() {

      @Override
      public void onCancel() {
       // Function to handle cancel event
      }

      @Override
      public void onComplete(Bundle values) {
       // Function to handle complete event
       // Edit Preferences and update facebook acess_token
       SharedPreferences.Editor editor = mPrefs.edit();
       editor.putString("access_token",
         facebook.getAccessToken());
       editor.putLong("access_expires",
         facebook.getAccessExpires());
       editor.commit();

       // Making Login button invisible
       btnFbLogin.setVisibility(View.INVISIBLE);

       // Making logout Button visible
       btnFbGetProfile.setVisibility(View.VISIBLE);

       // Making post to wall visible
       btnPostToWall.setVisibility(View.VISIBLE);

       // Making show access tokens button visible
       btnShowAccessTokens.setVisibility(View.VISIBLE);
      }

      @Override
      public void onError(DialogError error) {
       // Function to handle error

      }

      @Override
      public void onFacebookError(FacebookError fberror) {
       // Function to handle Facebook errors

      }

     });
  }
 }

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


 /**
  * Get Profile information by making request to Facebook Graph API
  * */
 @SuppressWarnings("deprecation")
 public void getProfileInformation() {
  mAsyncRunner.request("me", new RequestListener() {
   @Override
   public void onComplete(String response, Object state) {
    Log.d("Profile", response);
    String json = response;
    try {
     // Facebook Profile JSON data
     JSONObject profile = new JSONObject(json);
     
     // getting name of the user
     final String name = profile.getString("name");
     
     // getting email of the user
     final String email = profile.getString("email");
     
     runOnUiThread(new Runnable() {

      @Override
      public void run() {
       Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
      }

     });

     
    } catch (JSONException e) {
     e.printStackTrace();
    }
   }

   @Override
   public void onIOException(IOException e, Object state) {
   }

   @Override
   public void onFileNotFoundException(FileNotFoundException e,
     Object state) {
   }

   @Override
   public void onMalformedURLException(MalformedURLException e,
     Object state) {
   }

   @Override
   public void onFacebookError(FacebookError e, Object state) {
   }
  });
 }

 /**
  * Function to post to facebook wall
  * */
 @SuppressWarnings("deprecation")
 public void postToWall() {
  // post on user's wall.
  facebook.dialog(this, "feed", new DialogListener() {

   @Override
   public void onFacebookError(FacebookError e) {
   }

   @Override
   public void onError(DialogError e) {
   }

   @Override
   public void onComplete(Bundle values) {
   }

   @Override
   public void onCancel() {
   }
  });

 }

 /**
  * Function to show Access Tokens
  * */
 public void showAccessTokens() {
  String access_token = facebook.getAccessToken();

  Toast.makeText(getApplicationContext(),
    "Access Token: " + access_token, Toast.LENGTH_LONG).show();
 }
 
 /**
  * Function to Logout user from Facebook
  * */
 @SuppressWarnings("deprecation")
 public void logoutFromFacebook() {
  mAsyncRunner.logout(this, new RequestListener() {
   @Override
   public void onComplete(String response, Object state) {
    Log.d("Logout from Facebook", response);
    if (Boolean.parseBoolean(response) == true) {
     runOnUiThread(new Runnable() {

      @Override
      public void run() {
       // make Login button visible
       btnFbLogin.setVisibility(View.VISIBLE);

       // making all remaining buttons invisible
       btnFbGetProfile.setVisibility(View.INVISIBLE);
       btnPostToWall.setVisibility(View.INVISIBLE);
       btnShowAccessTokens.setVisibility(View.INVISIBLE);
      }

     });

    }
   }

   @Override
   public void onIOException(IOException e, Object state) {
   }

   @Override
   public void onFileNotFoundException(FileNotFoundException e,
     Object state) {
   }

   @Override
   public void onMalformedURLException(MalformedURLException e,
     Object state) {
   }

   @Override
   public void onFacebookError(FacebookError e, Object state) {
   }
  });
 }

}






You can download the source code First Android.

44 comments:

  1. Thanks Sunil for this wonderful article

    ReplyDelete
  2. how could i login from one activity and logout from other ?

    ReplyDelete
  3. thx guy! you save my app and time :D

    ReplyDelete
  4. Hello Sunil...
    I need to implement facebook friends invite .. if You have any knowledge ..Pls share.... ..waiting for your positive response

    ReplyDelete
    Replies
    1. Use this code

      private void sendRequestDialog() {
      Bundle params = new Bundle();
      params.putString("message", "Learn how to make your Android apps social");

      WebDialog requestsDialog = (
      new WebDialog.RequestsDialogBuilder(getActivity(),
      Session.getActiveSession(),
      params))
      .setOnCompleteListener(new OnCompleteListener() {

      @Override
      public void onComplete(Bundle values,
      FacebookException error) {
      if (error != null) {
      if (error instanceof FacebookOperationCanceledException) {
      Toast.makeText(getActivity().getApplicationContext(),
      "Request cancelled",
      Toast.LENGTH_SHORT).show();
      } else {
      Toast.makeText(getActivity().getApplicationContext(),
      "Network Error",
      Toast.LENGTH_SHORT).show();
      }
      } else {
      final String requestId = values.getString("request");
      if (requestId != null) {
      Toast.makeText(getActivity().getApplicationContext(),
      "Request sent",
      Toast.LENGTH_SHORT).show();
      } else {
      Toast.makeText(getActivity().getApplicationContext(),
      "Request cancelled",
      Toast.LENGTH_SHORT).show();
      }
      }
      }

      })
      .build();
      requestsDialog.show();
      }


      Refer here https://developers.facebook.com/docs/android/send-requests/

      Delete
  5. Hi Sunil ! I am new in android programming . Therefore, before trying your solution , I first tried something easier : https://developers.facebook.com/docs/android/scrumptious/authenticate/ The solution implements the use of two fragments : SplashFragment ( has the facebook login button ) and SelectionFragment ( splash screen announcing that you are logged ) .

    Once you start session, displays the "Remember browser" and " You have Already Authorized ... Cancel / Ok " screens and after that , it shows the welcome screen ( SelectionFragment ) and everything worked as expected.

    It works fine when I start session with facebook account that I used to generate the SHA1 Key.

    starting session with other Facebook accounts does not work. After entering another email and other password facebook account , displays the " Remember browser" if you want to keep the browser or not. Then return to the main screen where is the facebook login button ( SplashFragment ) .

    The reason is because it only works with the email I registered to generate the sha1 key? what do you think? Thanks for your time, sorry for my bad google traductor english . greetings . Adrian from Argentina

    ReplyDelete
    Replies
    1. I found the solution: deactivate sandbox mode from the dashboard facebook developers options!! i think you could delete my question!! byee!!

      Delete
    2. how to deactivate the sandbox mode?

      Delete
  6. Hi Sunil, I want to implement the facebook share dialog on my app. I have a tab layout using fragments and a viewpager. I also have a google map on my app, in the third tab. Now, on the fifth tab is the "Share on Facebook" tab. He can share when he is in a specific landmark, and in the "Share" post, it must include an image and a description about the landmark. I hope you can show me how. Many thanks and God Bless!

    ReplyDelete
  7. how to post my data from database in facebook ???????

    ReplyDelete
  8. But my problem is when i was logout i can not jump to the login activity or active again login activity so how i can achive ?? i as remove this problem to every time to uninstalling app. so give me some suggession .

    ReplyDelete
  9. Mr. Sunli...
    I try to implement your code in my apps.
    But i've a problem with android class name.
    I've a lot of activities. But i already set the main of my activity in my androidmanifests as the android class name.
    But when i run the application, it give me
    11-28 08:50:56.215: E/AndroidRuntime(16006): Process: co.id.catalyst.ayuberhemat, PID: 16006
    11-28 08:50:56.215: E/AndroidRuntime(16006): java.lang.NoClassDefFoundError: com.facebook.android.Facebook
    11-28 08:50:56.215: E/AndroidRuntime(16006): at co.id.catalyst.activity.LoginActivity.(LoginActivity.java:30)

    how do i solve it ? I'm new on developing android apps.
    Thank you

    ReplyDelete
    Replies
    1. Hi,

      Did you added the current Facebook library in your project. Then after you can make this. No class defined found error only cone when your library or any jar file not build in your project or Any class that you are using are not included in that library, See the things make according this.

      Delete
  10. Hi,
    I've tried to follow your tutorial as much as possible, but I'm stuck at fetching user's profile. The AsyncRunner.request is getting stuck. It shows the access token url of the user and nothing. The OnComplete overridden method is not getting called. Do you know any solution to this problem? Please help me if you do. Thanks.

    ReplyDelete
  11. HI Sunil,
    i want help from u,..how to fetch the friends from the Facebook to my activity(lazzy list activity)..plz help me

    ReplyDelete
  12. You have facebook SDK 3.0.6... can you please upgrade the sdk to 3.6.0 because some code has changed and your code gives all sorts of errors. Thanks.

    ReplyDelete
    Replies
    1. Yes, once get the time then come up with update with current sdk. Thanks

      Delete
  13. Hi Sunil,
    I want to get the Facebook Notifications,Inbox massages,friends requests in text views .
    Do you have any idea ?
    Thanks for your Nice documentation.

    ReplyDelete
  14. Hi Sunil,
    Do u have some idea how to enable like pages functionality of Facebook in Android.

    ReplyDelete
  15. Hi sunil
    Please tell me how to post custom stories on facebook from application like image ,title, desc, url ect....

    ReplyDelete
  16. Hi sunil,

    Do u have any idea on the concept i.e., where to place the downloaded api of facebook in our project like in which folder shall we place the facebook api in order to get that activated.. can u please suggest us on this area.. We are dealing on this concept as our final project on btech.. Reply soon..

    ReplyDelete
  17. How can I get user-birthday ? There is no user-birthday in json Array.

    ReplyDelete
  18. This post copied from androidhive :)

    link : http://www.androidhive.info/2012/03/android-facebook-connect-tutorial/

    ReplyDelete
    Replies
    1. Hey,Chinna atleast he posting some good examples..10000000000 dislike for your comment.

      Delete
  19. Thank Shunil Bhai.
    But whats is the -String FILENAME = "AndroidSSO_data"; used for?
    another thing.How am i going to set a predefined text for wall posting. Lets say i have another activity & in that activity i have a editText and a button. So, when user will write something in the editText & press the button-the activity will post the text from the editText to facebook. How to implement it? Plz help me.

    ReplyDelete
  20. hi sunil,how to get profile picture in this code?plz help

    ReplyDelete
  21. Hi Sunil, I am making an app that allows users to take pictures and then upload them to facebook. Is this possible ?

    ReplyDelete
  22. hi sunil thanks for coding ı tried one account it ok login but ı tried another account dont login ı saw log cat problem about permissions ı cant solve can you help me ?

    ReplyDelete
  23. Hi sunil, I was able to do this implementation on android but I need to use something called Facebook Gateway. There the login code is get implemented. After logging in I was able to take the permissions to access the profile for the user. Then I am again redirected to login button page but not to next activity. I want to move to next activity where it contain buttons like profile details, Friends etc. Help me out plz. The code below is wat I wrote for facebook gateway

    public void onClick(View paramAnonymousView) {

    FacebookGateway fbGateway = new FacebookGateway();
    fbGateway.setFacebookSession(new Session(getApplicationContext()));
    fbGateway.setDelegate(_this);
    fbGateway.login(_this);
    }
    });

    ReplyDelete
  24. Many thanks Sunil, my challenge is that i want to post comment with this facebook authentication code. The comment i'll post will only appear on the comment section of the app and not on Facebook's Wall.... Thanks and awaiting your reply.

    ReplyDelete
  25. The message 'openssl' is not recognized as an internal or external command,
    operable program or batch file.
    show to me when I enter C:\>keytool -exportcert -alias androiddebugkey -keystore "C:\Android\debug.keystore" | openssl sha1 -binary | openssl base64

    ReplyDelete
  26. how to post the images in facebook by using this?
    Thanks

    ReplyDelete
  27. how to like a page in facebook via android app

    ReplyDelete
  28. Jelly gamat atau sari teripang sudah sejak dahulu kala di gunakan
    sebagai obat alternatif untuk membantu pengobatan berbagai
    penyakit. ”Dalam sejarah Dunia online
    tradisional China teripang telah digunakan sejak lebih dari 1000 tahun obat herbal penyakit kista
    yang lalu untuk membantu mengatasi keluhan seperti menyembuhkan luka,Trik blogger pun ini bisa
    meredakan rasa sakit di persendian, memperlancar sirkulasi darah dan
    secara umum dikonsumsi Obat Tradisional Penyakit Tekanan Darah Tinggi sebagai hidangan spesial untuk menjaga kesehatan
    karena dinilai sebagai ginseng laut”. kecantikan
     Buah yang mungil dan memilki rasa asam dan manis kesehatan ini merupakan nenek
    moyang yang berasal dari eropa dan sekarang banyak di budidayakan di
    Negara kita.  Khasiat Tanaman Tono Blogger,
    Asma merupakan penyakit obstrupsi atau mungkin dengan kata lain
    penyempitan yg berulang dengan tanda-tanda klinis berbentuk batuk, kunjungi website
    mengek, serta sesak napas. Ada juga yg menuturkan bahwasanya penyakit
    asma Obat Tradisional Penyakit Ambeien dari situs ini melalui Cara Mengobati Penyakit Mioma teru dengan ini Obat Tradisional Penyakit Tekanan Darah Tinggi Obat Tradisional Untuk Kanker Paru Paru Ampuh - Obat herbal Penyakit Gula Darah Jika Anda memilih pengobatan kanker secara medis maka Darah Tinggi tindakan yang dapat dilakukan adalah dengan operasi pembedahan untuk mengangkat sel kanker, Menebak siapa daku terapi radiasi, kemoterapi, dan penyuntikan Photodynamic (PTD). Selain itu, Anda juga dapat memilih pengobatan kank baca selengkapnya


    Obat Untuk Kanker Otak,info selengkapnya disini kanker otak merupakan salah satu penyakit yang menyerang otak.kunjungi web Kesehatan inibaca selengkapnya dari mana dan kemana ini dia Masuk untuk disini,teruskan dengan sebuah penyakit  Obat Stroke Ampuh ,jangan lupa untuk mengunjungi   stroke  atau di sini kunjungi ini infonya , Demam Berdarah

    ReplyDelete
  29. Thank you for ur nice tutorial..
    Can you give me a tutorial for sharing link or publishing feed?

    ReplyDelete
  30. how can i code fb login in one activity and logout in another activity

    ReplyDelete
  31. Hello Sunil...
    I need to implement facebook page like ... mean it on button click open page and make user to like page if You have any knowledge ..Pls share.... ..waiting for your positive response

    ReplyDelete
  32. Hello Sunil,
    Super Work but i am facing some issue fb login not working on tablet but working fine in phone "http://stackoverflow.com/questions/25886676/facebook-sdk-not-working-in-tablet-android-it-work-fine-in-phone?" can you help me out

    ReplyDelete
  33. hello sunil,
    Nice tutorial.But just i need login process, after facebook login ,i want to redirect to my application Home page and login with different account is not possible. pls give me a solution

    ReplyDelete