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