Android Studio Add Facebook Login using Facebook SDK 4 Tutorial

How to integrate Facebook Login in android app and show get Facebook user profile image in app with name and email.

In this tutorial we would going to implement fully integrated Facebook login management system into android application using Facebook SDK 4. By implementing Facebook Login android application developer can directly login into any app without creating new account. So here is the complete step by step tutorial for Android Studio Add Facebook Login using Facebook SDK 4 Tutorial.

android-project-download-code-button

Before getting started with coding we need to follow the below steps to add our app on Facebook developers :-

1. Create a fresh project in Android Studio.

2. After done creating project open developers.facebook.com .

3. Login with your Facebook ID.

4. After successfully login Click on Create App button.

5. Enter Application display name and your contact email address . Then click on Create App ID .

6. At front of Facebook Login click on Get Started.

7. On Choose Platform Window click on Android .

8. Now skip to the 2nd step and open your Project’s build.gradle(Module:app) file.

9. Add repositories code just above the dependencies block like i did in below example, After that also add compile ‘com.facebook.android:facebook-android-sdk:4.+’ inside dependencies block.

repositories {
    mavenCentral()
}
compile 'com.facebook.android:facebook-android-sdk:4.+'

10. Now goto Tell Us about Your Android Project 3rd step and add your project package name Activity name in which your are going to implement Facebook login.

11. Next step is to generate development hast key, So read my this tutorial to Generate Hash Key for Facebook.

12. Copy the generated hash key into Key Hashes Box.

13. Now enable Sing in.

14. Follow all the steps written in below screenshots to add App id in your project. You can find your app id at the above top left side of your Facebook developers screen.

15. Now just click on next button till the end. Here you go now you have successfully add Facebook login to your project.

16. Add internet permission to your project.

<uses-permission android:name="android.permission.INTERNET"/>

Here you go all steps have been done. Now its time to start coding.

Code starts from here for project Android Studio Add Facebook Login using Facebook SDK 4 Tutorial.

Code for MainActivity.java file.

package com.android_examples.facebooklogin_android_examplescom;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import com.facebook.AccessTokenTracker;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginResult;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.login.widget.LoginButton;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.widget.ProfilePictureView;

public class MainActivity extends AppCompatActivity {

    CallbackManager callbackManager;
    TextView FacebookDataTextView;
    LoginButton loginButton;
    AccessTokenTracker accessTokenTracker;
    ProfilePictureView profilePictureView;
    String FacebookUserID ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Passing MainActivity in Facebook SDK.
        FacebookSdk.sdkInitialize(MainActivity.this);

        // Adding Callback Manager.
        callbackManager = CallbackManager.Factory.create();

        setContentView(R.layout.activity_main);

        // Assign TextView ID.
        FacebookDataTextView = (TextView)findViewById(R.id.TextView1);

        // Assign Facebook Login button ID.
        loginButton = (LoginButton)findViewById(R.id.login_button);

        profilePictureView = (ProfilePictureView) findViewById(R.id.profilePic);

        // Giving permission to Login Button.
        loginButton.setReadPermissions("email");

        // Checking the Access Token.
        if(AccessToken.getCurrentAccessToken()!=null){

            GraphLoginRequest(AccessToken.getCurrentAccessToken());

            // If already login in then show the Toast.
            Toast.makeText(MainActivity.this,"Already logged in",Toast.LENGTH_SHORT).show();

        }else {

            // If not login in then show the Toast.
            Toast.makeText(MainActivity.this,"User not logged in",Toast.LENGTH_SHORT).show();
        }

        // Adding Click listener to Facebook login button.
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>(){
            @Override
            public void onSuccess(LoginResult loginResult){

                // Calling method to access User Data After successfully login.
                GraphLoginRequest(loginResult.getAccessToken());
            }

            @Override
            public void onCancel(){

                Toast.makeText(MainActivity.this,"Login Canceled",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(FacebookException exception){

                Toast.makeText(MainActivity.this,"Login Failed",Toast.LENGTH_SHORT).show();
            }

        });

        // Detect user is login or not. If logout then clear the TextView and delete all the user info from TextView.
        accessTokenTracker = new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(AccessToken accessToken, AccessToken accessToken2) {
                if (accessToken2 == null) {

                    // Clear the TextView after logout.
                    FacebookDataTextView.setText("");
                    
                    // Clear the profilePictureView after logout.
                    profilePictureView.setProfileId(null);

                }
            }
        };
    }

    // Method to access Facebook User Data.
    protected void GraphLoginRequest(AccessToken accessToken){
        GraphRequest graphRequest = GraphRequest.newMeRequest(accessToken,
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {

                        try {

                            // Getting Facebook User ID into variable.
                            FacebookUserID = jsonObject.getString("id");

                            // Adding Facebook User Full name into TextView.
                            FacebookDataTextView.setText(FacebookDataTextView.getText() + "\nName : " + jsonObject.getString("name"));

                            // Adding Facebook User Email into TextView.
                            FacebookDataTextView.setText(FacebookDataTextView.getText() + "\nEmail : " + jsonObject.getString("email"));

                            // BY using FacebookUserID call profile pic from facebook server.
                            profilePictureView.setProfileId(FacebookUserID);
                        }
                        catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

        Bundle bundle = new Bundle();
        bundle.putString(
                "fields",
                "id,name,email"
        );
        graphRequest.setParameters(bundle);
        graphRequest.executeAsync();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        super.onResume();
        AppEventsLogger.activateApp(MainActivity.this);

    }

    @Override
    protected void onPause() {
        super.onPause();
        AppEventsLogger.deactivateApp(MainActivity.this);

    }
}

Code for activity_main.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:facebook="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    facebook:context="com.android_examples.facebooklogin_android_examplescom.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/TextView1"
        android:text=""
        android:textSize="20dp"
        android:gravity="center"
        android:textColor="#000"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <com.facebook.login.widget.ProfilePictureView
        android:id="@+id/profilePic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        facebook:preset_size="small"
        android:layout_below="@+id/TextView1"
        android:layout_marginTop="30dp"
        />

    <com.facebook.login.widget.LoginButton
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="30dp"
        android:layout_below="@+id/profilePic"
        android:layout_centerHorizontal="true"
        />

</RelativeLayout>

Code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android_examples.facebooklogin_android_examplescom">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id"
            />

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Screenshots:

Android Studio Add Facebook Login using Facebook SDK 4 Tutorial

Click here to download Android Studio Add Facebook Login using Facebook SDK 4 Tutorial project with source code.

3 Comments

  1. sdkInitialize is depricated. No longer needed to use that in SDK4

Leave a Reply

Your email address will not be published. Required fields are marked *