Facebook login in our Android app/ Sample example tutorial

By | June 3, 2020

What is Facebook Login: by integrating facebook log in our app we can login a user by their existing facebook account and get the user information Like Profile picture,User Name,Email,birthday,gender etc. So that we can identify a user.

In this tutorial, we will create a simple android app by  implementing Facebook login to  fetch user’s name &  profile picture, Email , gender  and display them on simple Layout.

STEP 1: Creating  NEW Android Project.

-Create a new project in android studio name it as myfblogin and package name is com.khushi.myfblogin.

-And i have activity named MainActivity.java and its layout file name is activity_main.xml.

STEP 2: Creating New App in facebook developer.

-(you must have a facebook account.)

-Goto http://developer.facebook.com/

-Click on My Apps> Add A New App.

-now give the name to your app and type email.

-Click on Create App.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

-Now note  down your App ID.

STEP 3: Integrating Facebook SDK: The Facebook Login SDK for Android is a component of the Facebook. To use the Facebook Login SDK in your project, make it a dependency in Maven, or download it. Choose the method you prefer,i m using it with maven dependency.

-Download and login into your facebook app.

-In your project, open your_app > Gradle Scripts > build.gradle (Project) make sure the following repository is listed in the buildscript { repositories {}}:

jcenter()

-In your project, open your_app > Gradle Scripts > build.gradle (Module: app) and add the following implementation statement to the dependencies{} section to depend on the latest version of the Facebook Login SDK:

implementation 'com.facebook.android:facebook-login:[5,6)'

-Build your project.

STEP 4: Edit Your Manifest: Add the following uses-permission element after the application element:

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

-Add the following meta-data element, an activity for Facebook, and an activity and intent filter for Chrome Custom Tabs inside your application element:

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

<activity android:name="com.facebook.FacebookActivity"
    android:configChanges=
        "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
    android:label="@string/app_name" />
<activity
    android:name="com.facebook.CustomTabActivity"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="@string/fb_login_protocol_scheme" />
    </intent-filter>
</activity>

STEP 5: Edit your Resources file: Open your- app>src>values>strings.xml file.

 <string name="app_name">myfblogin</string>
    <string name="facebook_app_id">1386921814984169</string>
    <string name="fb_login_protocol_scheme">fb1386921814984169</string>
    <string name="email">Email: </string>
    <string name="name">Facebook Name: </string>
    <string name="gender">Gender: </string>

-Add the following: here type yours app id and  fb_login_protocol_scheme(simply type fb before app id).

STEP 6: Adding details in your facebook app.

6.1 Associate Your Package Name and Default Class with Your App:

-GOTO: https://developers.facebook.com/apps/[your app id]/settings/basic/

-You need to provide platform information for each platform you deliver your app on. For each platform, go to Settings > Basic and click Add Platform.
-Add your Package Name: com.khushi.myfblogin
-Add your class name: com.khushi.myfblogin.MainActivity.java

6.2 Provide the Development and Release Key Hashes for Your App

Windows:You will need the following:

For Generating SHA1 on Windows we need to:
1) Download Openssl library.
– Download it from here(link:https://drive.google.com/open?id=1aq4UFJkJtQYDEnlW6aExdzKFbzZm6QGv).
– And Extract it to path C:\Program Files\
– Run command in command prompt:

	 set OPENSSL_CONF=C:\Program Files\\OpenSSL\bin\openssl.cfg
	

2) Make sure Java Runtime Environment is installed. Then Run the following command in Command Prompt:


"PATH_TO_JAVA_BIN\keytool.exe" -exportcert -alias androiddebugkey -keystore "C:\Users\YOUR_USER_NAME\.android\debug.keystore" | "PATH_TO_OPENSSL_LIBRARY\bin\openssl" sha1 -binary | ""PATH_TO_OPENSSL_LIBRARY\bin\openssl" base64

In the above command make changes according to your system. In our case Its as follows:

YOUR_USER_NAME= khushi
PATH_TO_OPENSSL_LIBRARY = C:\Program Files\OpenSSL
PATH_TO_JAVA_BIN = C:\Program Files\Java\jre1.8.0_251\bin

The final command will be as follows:


"c:\Program Files\Java\jre1.8.0_251\bin\keytool.exe" -exportcert -alias androiddebugkey -keystore "C:\Users\Khushi\.android\debug.keystore" | "C:\Program Files\OpenSSL\bin\openssl" sha1 -binary | "C:\Program Files\OpenSSL\bin\openssl" base64

After running this command it will ask for the android debug keystore password.
The password is :

android

You wil get the key hash as something similar to:

HCSloI6qlnHXBWZLScyWrW+MUP0=

-This command will generate a 28-character key hash unique to your development environment. You will need to provide a development key hash for the development environment of each person who works on your app.

6.3 Enable Single Sign On for Your App:
(If you would like your Android Notifications to have the ability to launch your app, enable single sign on.)

STEP 7: Add the Facebook login button: The simplest way to add Facebook Login to your app is to add LoginButton from the SDK. The LoginButton is a UI element that wraps functionality available in the LoginManager. When someone clicks on the button, the login is initiated with the permissions set in the LoginManager.

 <com.facebook.login.widget.LoginButton
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_gravity="center_horizontal" /></pre>

STEP 8: Add the following code in your activity_main.xml 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=".MainActivity">

    <LinearLayout
        android:id="@+id/layout_info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/login_button"
        android:layout_marginBottom="20dp"
        android:orientation="vertical"
       android:visibility="gone">


        <com.facebook.login.widget.ProfilePictureView
            android:id="@+id/image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/email"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/email"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
               />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/name"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/name"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
            />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/gender"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/gender"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                />
        </LinearLayout>
    </LinearLayout>

    <com.facebook.login.widget.LoginButton
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_gravity="center_horizontal" />
</RelativeLayout></pre>

STEP 9:  Now open MainActivity.java and do the below modifications-

9.1 Now create a callbackManager to handle login responses by calling CallbackManager.Factory.create.

CallbackManager callbackManager;
CallbackManager = CallbackManager.Factory.create();

9.2 Here you should write all the data permission you required.

loginButton.setPermissions(Arrays.asList("public_profile, email, user_birthday,user_gender"));

-To respond to a login result, register a callback with LoginManager.
-You add the LoginManager callback to your activity or fragment’s onCreate() method:

LoginManager.getInstance().registerCallback(callbackManager,
                new FacebookCallback&lt;LoginResult&gt;() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                         SendGraphRequest(loginResult.getAccessToken());
                    }

                    @Override
                    public void onCancel() {
                        // App code

                    }

                    @Override
                    public void onError(FacebookException error) {
                        Toast.makeText(MainActivity.this, "error to Login Facebook", Toast.LENGTH_SHORT).show();
                    }

                });

-If login succeeds, the LoginResult parameter has the new AccessToken, and the most recently granted or declined permissions. 

9.3 onSuccess(...) : And if success then onSucess(...) method is called and in this method we call SendGraphRequest(...) which will fetch user data in JSON OBJECT.

9.4 SendGraphRequest(...): By calling this method we get users data in JSON OBJECT and then this method call setProfileToView(...).

9.5 setProfileToView(...): This method get the data from JSON OBJECT and display it on simple layout.

9.6 onActivityResult(...): Finally, in your onActivityResult method, call callbackManager.onActivityResult to pass the login results to the LoginManager via callbackManager.
package com.khushi.myfblogin;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.facebook.login.widget.ProfilePictureView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;
LoginButton loginButton;
TextView email,gender,facebookName;
ProfilePictureView profilePictureView;
LinearLayout infoLayout;
AccessTokenTracker accessTokenTracker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
AccessToken accessToken = AccessToken.getCurrentAccessToken();
boolean isLoggedIn = accessToken != null && !accessToken.isExpired();
if(isLoggedIn){
SendGraphRequest(accessToken);
}

email = (TextView)findViewById(R.id.email);
facebookName = (TextView)findViewById(R.id.name);
gender = (TextView)findViewById(R.id.gender);
profilePictureView = (ProfilePictureView)findViewById(R.id.image);
infoLayout = (LinearLayout)findViewById(R.id.layout_info);
// infoLayout.setVisibility(View.GONE);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setPermissions(Arrays.asList("public_profile, email, user_birthday,user_gender"));

LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {

SendGraphRequest(loginResult.getAccessToken());

}

@Override
public void onCancel() {
// App code

}

@Override
public void onError(FacebookException error) {
Toast.makeText(MainActivity.this, "error to Login Facebook", Toast.LENGTH_SHORT).show();
}

});

}

private void SendGraphRequest(AccessToken token) {
//App code
GraphRequest request = GraphRequest.newMeRequest(
token,
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.v("Main", response.toString());
setProfileToView(object);
}
});
Bundle parameters = new Bundle();
parameters.putString("fields","id,name,email,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
//hiding infolayout if iser currently logged out.

accessTokenTracker = new AccessTokenTracker() {
@Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken,
AccessToken currentAccessToken) {
if (currentAccessToken == null) {
infoLayout.setVisibility(View.GONE);
//write your code here what to do when user logout
}
}
};
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
private void setProfileToView(JSONObject jsonObject) {
try {
System.out.println("FB json object : "+jsonObject.toString());
email.setText(jsonObject.getString("email"));
gender.setText(jsonObject.getString("gender"));
facebookName.setText(jsonObject.getString("name"));

profilePictureView.setPresetSize(ProfilePictureView.NORMAL);
profilePictureView.setProfileId(jsonObject.getString("id"));
infoLayout.setVisibility(View.VISIBLE);
} catch (JSONException e) {
e.printStackTrace();
}
}

}

1,158 total views, 3 views today

(Visited 63 times, 1 visits today)