Android Get Facebook Login User Information Using Graph API Android Studio Example Tutorial

How to get Facebook login user data ID, first name, last name, email, gender, link, locale and account verified status programmatically.

In this tutorial we would going to implement Facebook Login in our android application using Android Studio. After successfully login we would going to show logged user personal information which we want to access like User full name, First name, Last Name, Gender, Complete Facebook Profile link etc. So here is the complete step by step tutorial for Android Get Facebook Login User Information Using Graph API Android Studio Example 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 Get Facebook Login User Information Using Graph API Android Studio Example Tutorial.

Code for MainActivity.java file.

package com.android_examples.facebookgraphapi_android_examplescom;
import android.os.Bundle;
import android.widget.TextView;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
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;


public class MainActivity extends AppCompatActivity {

    // Declaring Variables.
    CallbackManager callbackManager;
    TextView FacebookDataTextView;
    LoginButton loginButton;
    AccessTokenTracker accessTokenTracker;

    @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);

        // 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("");

                }
            }
        };
    }

    // 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 {

                            // Adding all user info one by one into TextView.
                            FacebookDataTextView.setText("ID: " + jsonObject.getString("id"));

                            FacebookDataTextView.setText(FacebookDataTextView.getText() + "\nName : " + jsonObject.getString("name"));

                            FacebookDataTextView.setText(FacebookDataTextView.getText() + "\nFirst name : " + jsonObject.getString("first_name"));

                            FacebookDataTextView.setText(FacebookDataTextView.getText() + "\nLast name : " + jsonObject.getString("last_name"));

                            FacebookDataTextView.setText(FacebookDataTextView.getText() + "\nEmail : " + jsonObject.getString("email"));

                            FacebookDataTextView.setText(FacebookDataTextView.getText() + "\nGender : " + jsonObject.getString("gender"));

                            FacebookDataTextView.setText(FacebookDataTextView.getText() + "\nLink : " + jsonObject.getString("link"));

                            FacebookDataTextView.setText(FacebookDataTextView.getText() + "\nTime zone : " + jsonObject.getString("timezone"));

                            FacebookDataTextView.setText(FacebookDataTextView.getText() + "\nLocale : " + jsonObject.getString("locale"));

                            FacebookDataTextView.setText(FacebookDataTextView.getText() + "\nUpdated time : " + jsonObject.getString("updated_time"));

                            FacebookDataTextView.setText(FacebookDataTextView.getText() + "\nVerified : " + jsonObject.getString("verified"));
                        }
                        catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

        Bundle bundle = new Bundle();
        bundle.putString(
                "fields",
                "id,name,link,email,gender,last_name,first_name,locale,timezone,updated_time,verified"
        );
        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:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.android_examples.facebookgraphapi_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.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/TextView1"
        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.facebookgraphapi_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 Get Facebook Login User Information Using Graph API Android Studio Example Tutorial

Click here to download Android Get Facebook Login User Information Using Graph API Android Studio Example Tutorial project with source code.

5 Comments

  1. Nice work…thanks
    Could you pleas write tutorial about one to one instant messaging Using PHP MySQL JSON….

  2. SaravanaMoorthy

    Nice work…
    how to get Profile Picture by the same way.

Leave a Reply

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