Implementing Facebook Login And Fetching Profile Data In Android

Implementing Facebook Login And Fetching Profile Data In Android
Most of the well-known apps today on the Android Play Store which needs Login to use the app have the Social Integration in them. By Social Integration, I mean that the users can login to their app using the already logged in Social Platforms like Facebook, Twitter, Google+.

So today we will the learning to do the same. In this tutorial, we will learn "How To Implement Facebook Login To Android App And Also How To Fetch The Facebook Users Profile Data From It Using The Facebook SDK v4.3".




What Will It Look Like?

Facebook Login Android Project In Action

Creating Facebook App

To make an Android app with Facebook Login, we need to have a Facebook App. So first we will create a new Facebook App. Let's Begin.

Step 1. Firstly go to Apps page of Facebook Developers website and click on Add a New App button.
Create A New Facebook App

Step 2. Select Android platform and then enter the name of your app. After you have entered a name for your app, click on the Create New Facebook App ID button.
Enter The Name Of Facebook App To Be Created

Step 3. On the next popup, you can see that there will be a question like "Is this a test version of another app?", so let it be NO. Then select the category for your app and Create App.

Step 4. After your app is created, again go to Apps page of Facebook Developers and you will find your new app there. So go on and click on you newly create app.

Step 5. After you click on your app, you will be taken to your Apps Dashboard. On the Dashboard page click on Settings.
Select The Settings Page

Step 6. On the Settings page, click on Add Platform button and select Android as the platform.
Add Platform To Your New App

Step 7. Now on the Settings page, there will be a new section for Android. So we need to enter some information into the app before beginning the actual development. Enter the following information.

  • Google Play Package Name: In this field, you need to enter you apps package name.
  • Class Name: In this field, you need to enter Activity's Name which you want Facebook to open.
  • Key Hashes: In this field, you need to enter the Key Hashes. Key Hashes are nothing but 'Digital Signatures' for your app which you need to specify in your apps settings. You need to generate this Key Hashes using your Terminal or Command Prompt.
For generating the key hash, you need to execute the below command and then enter the Keystore password to get the key hash. Enter the password as android.

For Windows Users
keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl
base64

For OSx and Linux Users
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

It will look like in the below image.
Enter Android Information To Facebook App

Step 8. Now, enter your Email ID into the Contact Email field on Settings page.
Enter Contact Email To Facebook App

Step 9. Finally, click on Save Settings and note down the Apps ID  for further use.

Step 10. Go to Status And Reviews page of App Dashboard.
Go to Status And Reviews Page

Step 11. Finally make your newly created app Public.
Enable Your Facebook App For Public

Creating Android Application

Step 1. Open Android Studio and create a new blank project by navigating to File => New Project and then fill other details.
Note: The package name must be same as we had entered in the Facebook Apps Settings.

Step 2. The first thing to be done is adding the dependencies. So open the build.gradle file and add the following line in dependencies.
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.facebook.android:facebook-android-sdk:4.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
}

Then also add this below snippet to your build.gradle file.
repositories {
    mavenCentral()
}

So now your build.gradle file must look something like this.
apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "21.1.2"

    repositories {
        mavenCentral()
    }

    defaultConfig {
        applicationId "com.androidsphere.facebooklogindemo"
        minSdkVersion 10
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.facebook.android:facebook-android-sdk:4.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
}

Step 3. Now, open your Android Manifest.xml file. After opening add the INTERNET permissions to it.
<uses-permission android:name="android.permission.INTERNET"/>

After that, add the following Meta Data to your Application.
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
Create a string with the name in android:value attributes value and it's string must be the App ID of our App.

And then finally add the below activity to your Application.
<activity android:name="com.facebook.FacebookActivity"
          android:configChanges=
              "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
          android:theme="@android:style/Theme.Translucent.NoTitleBar"
          android:label="@string/app_name" />

Step 4. Now open your activity_main.xml in res => layout directory and add an ImageView, a TextView and Facebook Login button as given below in below code.
<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"
                android:padding="16dp"
                tools:context=".MainActivity">

    <!--This is for displaying the Profile Image-->
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/profile_image"
        android:src="@drawable/com_facebook_profile_picture_blank_square"
        android:layout_above="@+id/profile_info_textview"
        android:layout_alignParentTop="true"
        android:scaleType="fitCenter"/>

    <!--This is for displaying the Profile Info-->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text=""
        android:id="@+id/profile_info_textview"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"/>

    <!--This is the Login Button of Facebook-->
    <com.facebook.login.widget.LoginButton
        android:id="@+id/login_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"/>

</RelativeLayout>

Step 5. Finally, open your MainActivity.java file and paste the below code to it.
package com.androidsphere.facebooklogindemo;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.squareup.picasso.Picasso;


public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    ImageView profileImageView;
    TextView profileInfoTextView;
    CallbackManager callbackManager;
    FacebookCallback<LoginResult> facebookCallback;
    ProfileTracker profileTracker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Initialize Facebook SDK
        FacebookSdk.sdkInitialize(getApplicationContext());

        //Initialize the CallbackManager using the
        // CallbackManager.Factory.create() method to
        // create a new instance of it.
        callbackManager = CallbackManager.Factory.create();

        setContentView(R.layout.activity_main);

        //Initialize the ImageView and TextView
        profileImageView = (ImageView) findViewById(R.id.profile_image);
        profileInfoTextView = (TextView) findViewById(R.id.profile_info_textview);

        //Initialize the FacebookCallback and then override its methods
        // for performing actions.
        facebookCallback = new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                //This code will be performed when a user is
                // successfully logged in.
                Log.d(TAG, "FacebookCallback was Successful");
            }

            @Override
            public void onCancel() {
                //This code will be performed when a user
                // login is cancelled.
                Log.d(TAG, "FacebookCallback Cancelled");
            }

            @Override
            public void onError(FacebookException e) {
                //This code will be performed when a users login
                // attempt gets errors.
                Log.d(TAG, "FacebookCallback had Errors with \n" + e);
            }
        };

        //Initialize loginButton and register the
        // CallbackManager and FacebookCallback
        LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
        loginButton.registerCallback(callbackManager,facebookCallback);

        //Initialize the ProfileTracker and override its
        // onCurrentProfileChanged(...) method.
        profileTracker = new ProfileTracker() {
            @Override
            protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
                //Whenever the user profile is changed,
                //this method will be called.
                if (newProfile == null) {
                    profileImageView.setImageResource(R.drawable.com_facebook_profile_picture_blank_square);
                    profileInfoTextView.setText("");
                }else{
                    setUpImageAndInfo(newProfile);
                }
            }
        };
        profileTracker.startTracking();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Profile userProfile = Profile.getCurrentProfile();
        if (userProfile != null){
            setUpImageAndInfo(userProfile);
        }else{
            Log.d(TAG,"Profile is Null");
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
        profileTracker.stopTracking();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //When the login  button is clicked and user logs in.
        // After that, onActivityResult method is called
        callbackManager.onActivityResult(requestCode, resultCode, data);

    }

    public void setUpImageAndInfo(Profile userProfile) {
        //This method will fill up the ImageView and TextView
        // that we initialized before.
        final String userInfo = "<u>First Name:</u> " + userProfile.getFirstName() +
                "<br/><u>Last Name:</u> " + userProfile.getLastName() +
                "<br/><u>User Id:</u> " + userProfile.getId() +
                "<br/><u>Profile Link:</u> " + userProfile.getLinkUri().toString();
        profileInfoTextView.setText(Html.fromHtml(userInfo));

        //I am using the Picasso library to download the image
        // from URL and then load it to the ImageView.
        Picasso.with(this)
                .load("https://graph.facebook.com/" + userProfile.getId().toString() + "/picture?type=large")
                .into(profileImageView);
    }


}

Let's Understand What's Going On

First things first, always initialize the FacebookSdk first using the FacebookSdk.sdkInitialize() method.
In our activity_main.xml file, we had added Facebook Login button. So here in MainActivity.java we need to initialize that button and register it to FacebookCallback using the CallbackManager. But, the main part of updating the UI is done by the Profile Tracker which is used to detect the change in the user profile and update the profile picture and profile information on the screen. I have created a method called setUpImageAndInfo(profile) which takes profile object as a parameter to display the updated the information from that profile to the screen.

Step 6. So now finally, you have a working implementation of Facebook Login in Android using Facebook SDK v4.3. Go on and Run the project.

No comments:

Post a Comment