Mar 18, 2013

Android : Login with Facebook SDK 3.0


Introduction
The goal of this article is explain simplest way to use Facebook for Login and fetch user details including Email Address. 

The Facebook SDK for Android is the easiest way to integrate your Android app with Facebook's platform. 

What's new in Facebook SDK 3.0
  • Simplified user session management
  • Better Facebook APIs support
  • Ready-to-Use native UI views
  • Mobile install measurement
Prerequisite
1. Facebook Android SDK 3.0 - Download
2. Facebook API Key from Facebook Application - Detail
3. Hash Key of your debug certificate  - Detail


Step 1 : Create Android Project named "FacebookTest"
Step 2 : Import FacebookSDK in eclipse
Step 3 : Add Reference of Facebook SDK in FacebookTest Project



Step 4 : Add app_id in strings.xml, replace your facebook api key in following code.

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

    <string name="app_name">FacebookTest</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="app_id">YOUR_FACEBOOK_API_KEY</string>

</resources>

Step 5 : Add meta-date tag and LoginActivity in AndroidManifest.xml. In this demo I am using LoginButton provided by Facebook SDK, It is also possible to user our native Button for Login. We also require to register LoginActivity. LoginActivity & LoginButton are available in Facebook SDK.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.kpbird.facebooktest"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" />
    <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" >
        <activity
            android:name="com.kpbird.facebooktest.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>
         <activity android:name="com.facebook.LoginActivity"
           android:theme="@android:style/Theme.Translucent.NoTitleBar"
           android:label="@string/app_name" />
         <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id"/>
    </application>
</manifest>

Step 6 : Add Facebook Login button in activity_main.xml, Main activity contains TextView and LoginButton. TextView will display user's email address.
<RelativeLayout 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"
    tools:context=".MainActivity" >

     <TextView
         android:id="@+id/lblEmail"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentTop="true"
         android:layout_centerHorizontal="true"
         android:layout_marginTop="144dp"
         android:text="Email ID : "
         android:textAppearance="?android:attr/textAppearanceLarge" />

<com.facebook.widget.LoginButton
         android:id="@+id/authButton"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentTop="true"
         android:layout_centerHorizontal="true"
         android:layout_marginTop="45dp" />

</RelativeLayout>

Step 7 : Open MainActivity.java and write following code. Following is very simple code, you just need to take few importent things 
  • Override onActivityResult to get LoginButton Events
  • Set permission as per your requirement
  • executeMe request to fetch user detail and email
  • fetch email address from user object
package com.kpbird.facebooktest;

import java.util.Arrays;

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

import com.facebook.FacebookException;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.OnErrorListener;

public class MainActivity extends Activity {

 private String TAG = "MainActivity";
 private TextView lblEmail;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  lblEmail = (TextView) findViewById(R.id.lblEmail);
  
  LoginButton authButton = (LoginButton) findViewById(R.id.authButton);
  authButton.setOnErrorListener(new OnErrorListener() {
   
   @Override
   public void onError(FacebookException error) {
    Log.i(TAG, "Error " + error.getMessage());
   }
  });
  // set permission list, Don't foeget to add email
  authButton.setReadPermissions(Arrays.asList("basic_info","email"));
  // session state call back event
  authButton.setSessionStatusCallback(new Session.StatusCallback() {
   
   @Override
   public void call(Session session, SessionState state, Exception exception) {
    
    if (session.isOpened()) {
              Log.i(TAG,"Access Token"+ session.getAccessToken());
              Request.executeMeRequestAsync(session,
                      new Request.GraphUserCallback() {
                          @Override
                          public void onCompleted(GraphUser user,Response response) {
                              if (user != null) { 
                               Log.i(TAG,"User ID "+ user.getId());
                               Log.i(TAG,"Email "+ user.asMap().get("email"));
                               lblEmail.setText(user.asMap().get("email").toString());
                              }
                          }
                      });
          }
    
   }
  });
 }

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

}


Change Login/Logout text of LoginButton.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:fb="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.facebook.widget.LoginButton
         android:id="@+id/activity_login_facebook_btn_login"
         android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="15dp"
        fb:login_text="Login with Facebook"
     fb:logout_text="Logout"
         />

</RelativeLayout>

Read More



32 comments:

  1. Bruno Lemos3:35 PM

    Hi I follow your articl, by tway nice one!
    I am always getting Error inflating class com.facebook.widget.LoginButton
    Do you have a clue? Thanx

    ReplyDelete
  2. kpbird3:40 PM

    Hello JB L,


    Can you please post logcat trace ?


    I have tested in Android 4.0 with Activity. are you using same ?
    I have experience inflating error in SharelockActionbar with FragmentActivity.

    ReplyDelete
  3. Bruno Lemos2:04 AM

    Hi thanx for reply. LogCat:

    03-21 20:32:54.558: E/AndroidRuntime(810): FATAL EXCEPTION: main
    03-21 20:32:54.558: E/AndroidRuntime(810): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.galaxys3group/com.example.galaxys3group.MainActivity}: android.view.InflateException: Binary XML file line #17: Error inflating class com.facebook.widget.LoginButton
    03-21 20:32:54.558: E/AndroidRuntime(810): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
    03-21 20:32:54.558: E/AndroidRuntime(810): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
    03-21 20:32:54.558: E/AndroidRuntime(810): at android.app.ActivityThread.access$600(ActivityThread.java:141)
    03-21 20:32:54.558: E/AndroidRuntime(810): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
    03-21 20:32:54.558: E/AndroidRuntime(810): at android.os.Handler.dispatchMessage(Handler.java:99)
    03-21 20:32:54.558: E/AndroidRuntime(810): at android.os.Looper.loop(Looper.java:137)
    03-21 20:32:54.558: E/AndroidRuntime(810): at android.app.ActivityThread.main(ActivityThread.java:5041)
    03-21 20:32:54.558: E/AndroidRuntime(810): at java.lang.reflect.Method.invokeNative(Native Method)
    03-21 20:32:54.558: E/AndroidRuntime(810): at java.lang.reflect.Method.invoke(Method.java:511)
    03-21 20:32:54.558: E/AndroidRuntime(810): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    03-21 20:32:54.558: E/AndroidRuntime(810): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    03-21 20:32:54.558: E/AndroidRuntime(810): at dalvik.system.NativeStart.main(Native Method)
    03-21 20:32:54.558: E/AndroidRuntime(810): Caused by: android.view.InflateException: Binary XML file line #17: Error inflating class com.facebook.widget.LoginButton
    03-21 20:32:54.558: E/AndroidRuntime(810): at android.view.LayoutInflater.createView(LayoutInflater.java:613)
    03-21 20:32:54.558: E/AndroidRuntime(810): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
    03-21 20:32:54.558: E/AndroidRuntime(810): at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
    03-21 20:32:54.558: E/AndroidRuntime(810): at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
    03-21 20:32:54.558: E/AndroidRuntime(810): at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
    03-21 20:32:54.558: E/AndroidRuntime(810): at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
    03-21 20:32:54.558: E/AndroidRuntime(810): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:270)
    03-21 20:32:54.558: E/AndroidRuntime(810): at android.app.Activity.setContentView(Activity.java:1881)
    03-21 20:32:54.558: E/AndroidRuntime(810): at com.example.galaxys3group.MainActivity.onCreate(MainActivity.java:28)
    03-21 20:32:54.558: E/AndroidRuntime(810): at android.app.Activity.performCreate(Activity.java:5104)
    03-21 20:32:54.558: E/AndroidRuntime(810): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
    03-21 20:32:54.558: E/AndroidRuntime(810): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
    03-21 20:32:54.558: E/AndroidRuntime(810): ... 11 more
    03-21 20:32:54.558: E/AndroidRuntime(810): Caused by: java.lang.reflect.InvocationTargetException
    03-21 20:32:54.558: E/AndroidRuntime(810): at java.lang.reflect.Constructor.constructNative(Native Method)
    03-21 20:32:54.558: E/AndroidRuntime(810): at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
    03-21 20:32:54.558: E/AndroidRuntime(810): at android.view.LayoutInflater.createView(LayoutInflater.java:587)
    03-21 20:32:54.558: E/AndroidRuntime(810): ... 22 more
    03-21 20:32:54.558: E/AndroidRuntime(810): Caused by: java.lang.NoClassDefFoundError: com.facebook.android.R$color
    03-21 20:32:54.558: E/AndroidRuntime(810): at com.facebook.widget.LoginButton.(LoginButton.java:204)
    03-21 20:32:54.558: E/AndroidRuntime(810): ... 25 more

    ReplyDelete
  4. Bruno Lemos4:37 AM

    Hey hust fixed it! mismatch references. Thanx it works!

    ReplyDelete
  5. Bruno Lemos4:37 AM

    hust = just

    ReplyDelete
  6. Kevin5:08 PM

    sorry, row 47, session.isOpened() is always false for me.
    App loaded, I click on login button, I accept conditions, and then session.isOpened is false.

    Why? Can you help me, please?

    Thanks

    ReplyDelete
  7. just awesome tutorial... keep it ...

    ReplyDelete
  8. Hi when I tried log in button, it just returned to log in screen ? can you help me

    ReplyDelete
  9. arun pathania8:45 PM

    Hi when I Clicked log in button, after filling email/password it return in login ? I want to open other activity with login with fatch user details i need urgent please advice me ..!!

    ReplyDelete
  10. Hi when I tried log in button, it just returned to log in screen. Its not showing me my email.

    no logs are displayed of the application

    ReplyDelete
  11. Have you Found the solution for this situation, please help me :(

    ReplyDelete
  12. Yes, mine works now. Can you post your log cat here ?

    ReplyDelete
  13. Rafiqunnabi Nayan3:19 PM

    I've been searching for a tutorial like this for the last 2 days. Each and every result I found are either over complicated or do not work. You saved me.

    I don't know why facebook does not know how to write simple tutorials. The sample tutorials they provide deals a lot with Fragment, UI or other unnecessary components.

    ReplyDelete
  14. Hyeong Gyu Jeong1:48 PM

    Hi, your post is really great for me. But I have faced a trouble with special case. If there is facebook application for android in my device, it didn't work. I tried SSO.. but it is deprecated.. so, how can i use this facebook login where the facebook application in device ? Thanks !!

    ReplyDelete
  15. ninjadragon4:46 PM

    cheers bro

    ReplyDelete
  16. chuong lam9:16 PM

    Hi, i followed your instruction, but I still can't add FacebookSDK to my project. I click add button to choose the FacebookSDK -> OK. Then I re-open the properties for my project -> Android, oh no, it's not added. Help me, please.
    I've tried some tutorials, but it's still that error.

    ReplyDelete
  17. authButton.setSessionStatusCallback(new Session.StatusCallback() i have take errror this row like that :"Session.StatusCallback cannot be resolved to a type" have can i fix ?

    ReplyDelete
  18. Jim Nave9:41 AM

    executeMeRequestAsync() is deprecated. Do you have a solution of how to use: newMeRequest()?

    ReplyDelete
  19. Asmaa Damoh1:05 AM

    Nice tutorial (y) Good work :)
    For who don't know how to integrate Facebook SDK in their project , here a good tutorial who explain how to integrate it step by step
    http://www.happycodingwithdjo.com/facebook-sdk-in-android-application/

    ReplyDelete
  20. Asmaa Damoh1:07 AM

    Hello

    here a good tutorial, they explain how to integrate Facebook SDK step by step
    http://www.happycodingwithdjo.com/facebook-sdk-in-android-application/

    ReplyDelete
  21. Asmaa Damoh2:13 AM

    Hello Aahna , how do you solve it ? I have the same problem ,so can you please help me

    ReplyDelete
  22. christowly9:42 AM

    dude, how you solve the problem ?? I still stuck.
    No email display on page.

    ReplyDelete
  23. christowly9:57 AM

    I try to login but the code doesn't get the email
    It send me back to login page. What's wrong ??

    ReplyDelete
  24. 陳萱翰8:27 AM

    Hello:
    Thanks a lot about your example .
    I try to use your example , but there have some bug

    I want to ask about this bug if you were meet it . thanks.

    12-24 10:02:00.836: E/AndroidRuntime(3736): FATAL EXCEPTION: main

    12-24 10:02:00.836: E/AndroidRuntime(3736): java.lang.NoClassDefFoundError: android.support.v4.content.LocalBroadcastManager

    12-24 10:02:00.836: E/AndroidRuntime(3736): at com.facebook.internal.SessionTracker.(SessionTracker.java:76)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at com.facebook.widget.LoginButton.finishInit(LoginButton.java:533)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at com.facebook.widget.LoginButton.onFinishInflate(LoginButton.java:526)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at android.view.LayoutInflater.rInflate(LayoutInflater.java:774)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at android.view.LayoutInflater.inflate(LayoutInflater.java:498)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at android.view.LayoutInflater.inflate(LayoutInflater.java:398)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at android.view.LayoutInflater.inflate(LayoutInflater.java:354)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:361)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at android.app.Activity.setContentView(Activity.java:1956)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at com.example.kpbird.MainActivity.onCreate(MainActivity.java:28)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at android.app.Activity.performCreate(Activity.java:5372)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at android.app.ActivityThread.access$700(ActivityThread.java:159)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at android.os.Handler.dispatchMessage(Handler.java:99)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at android.os.Looper.loop(Looper.java:137)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at android.app.ActivityThread.main(ActivityThread.java:5419)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at java.lang.reflect.Method.invokeNative(Native Method)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at java.lang.reflect.Method.invoke(Method.java:525)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)

    12-24 10:02:00.836: E/AndroidRuntime(3736): at dalvik.system.NativeStart.main(Native Method)

    ReplyDelete
  25. shiva5:36 PM

    Thanks for this tutorial.

    ReplyDelete
  26. harshal6:32 PM

    As simple and precise as it gets.well written !! Thanks a ton
    @Rafiqunnabi Nayan - can't agree more with you,facebook's documentation sucks!!!

    ReplyDelete
  27. Aditya Delightful Guy6:38 PM

    Please tell to how to set auto authenticate option for facebook in android........?????

    ReplyDelete
  28. Simone Murtas5:00 PM

    Hi!! have you solved?

    ReplyDelete
  29. Vihang Joshi3:05 PM

    Thanks for this.. I've found the easiest way to login with facebook among what articles I've found. Do you have friends list demo ? I want it. Can you share its code just like you did for login ?

    ReplyDelete
  30. PremierITA3:05 AM

    Have you tried with fragment?

    ReplyDelete
  31. hi, I'm using your code for my sample, but I can not run this project, while add Facebook Button Login, this project can't be run. and when I delete this control (Facebook Login button) this Project is run, but not have controls login.

    ReplyDelete
  32. Hi have you solved this problem? Thanks ?

    ReplyDelete