Login With Facebook Android Studio using Facebook SDK

Total Views : 148
Zoom In Zoom Out Read Later Print

Hello friends, welcome to this tutorial. In this tutorial we will create a login with facebook android app using android studio and Facebook SDK.

Step#1 :

  • Create New Project

Step#2 :

Add following line to your build.gradle dependencies and build your project.

implementation 'com.facebook.android:facebook-android-sdk:4.38.1'

Step#3 :

Create your development and release key hashes.To integrate Android App and Facebook, we need to add Android key hash for development environment. if your app has already been published on store, you should add both your release key hash and Android key hash for your development.

Key hash

Open Android Terminal :

For Debug Build(Go to your debug.keystore path in the terminal and then run this command):
keytool -exportcert -alias androiddebugkey -keystore debug.keystore | openssl sha1 -binary | openssl base64

For Release Build:
keytool -exportcert -alias <aliasName> -keystore <keystoreFilePath> | openssl sha1 -binary | openssl base64

NOTE :
Make sure In both case it may ask for password. If it does not asks for password it's ok. Default password is android.

Step#4 :

  • Go to https://developers.facebook.com/. If you have not registered yourself as a developer yet then facebook will ask you to register as a developer. Simply register as a developer.
  • From the top navigation menu hover over my apps.
  • Then click add a new app.
  • Enter display name and contact email then click Create App ID.
  • Select Facebook Login from available options.
  • You will asked to select a platform, click on android.
  • You will be asked for app package name and activity. you can skip them if you app is not available on play store.
  • Enter previously generated keys hash keys.
  • Click save then Next.

Step#5 :

  • Open your /app/res/values/strings.xml file.
  • Add the following (Change as you app say):

APP ID

<string name="facebook_app_id">53412327XXXXXXX</string>
<string name="fb_login_protocol_scheme">fb53412327XXXXXXX</string>

  • Open the /app/manifest/AndroidManifest.xml file.
  • Add the following uses-permission element :

PERMISSION

<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

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

<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">
<activity
android:name=".MainActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<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>
<activity android:name=".UserProfile"></activity>
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" />
</application>
</manifest>

Ok, So far we have created our app and done with project setup now, let's code...


Add the Facebook Login Button

To add the Facebook Login button, first add it to your layout XML file

Facebook Login Button

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

Create a Callback

Callback

public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
}
}

Set Read Permission

Read Permission

public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("email");
}
}

Register Callback

Register Callback

public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("email");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
getUserDetails(loginResult);
}
@Override
public void onCancel() {
// Your code
}
@Override
public void onError(FacebookException exception) {
// Your code
}
});
}
}

Add onActivityResult

Finally, in your onActivityResult method, call callbackManager.onActivityResult to pass the login results to the LoginManager via callbackManager.

onActivityResult

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

Get User Profile

getUserDetails()

protected void getUserDetails(LoginResult loginResult) {
GraphRequest data_request = GraphRequest.newMeRequest(
loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted( JSONObject json_object, GraphResponse response) {
Intent intent = new Intent(MainActivity.this, UserProfile.class);
intent.putExtra("userProfile", json_object.toString());
startActivity(intent);
}

});
Bundle permission_param = new Bundle();
permission_param.putString("fields", "id,name,email,picture.width(120).height(120)");
data_request.setParameters(permission_param);
data_request.executeAsync();

}

activity_main.xml

<?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:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

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

</RelativeLayout>

MainActivity.java

package com.prodevsblog.facebooklogin;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
init();
}
void init(){
callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = findViewById(R.id.login_button);
loginButton.setReadPermissions("email");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
getUserDetails(loginResult);
}
@Override
public void onCancel() {
// Your code
}
@Override
public void onError(FacebookException exception) {
// Your code
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}

protected void getUserDetails(LoginResult loginResult) {
GraphRequest data_request = GraphRequest.newMeRequest(
loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted( JSONObject json_object, GraphResponse response) {
Intent intent = new Intent(MainActivity.this, UserProfile.class);
intent.putExtra("userProfile", json_object.toString());
startActivity(intent);
}

});
Bundle permission_param = new Bundle();
permission_param.putString("fields", "id,name,email,picture.width(120).height(120)");
data_request.setParameters(permission_param);
data_request.executeAsync();

}

protected void onResume() {
super.onResume();
AppEventsLogger.activateApp(this);
}
@Override
protected void onPause() {
super.onPause();
AppEventsLogger.deactivateApp(this);
}
}

activity_user_profile.xml

<?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"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:context=".UserProfile">

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/profilePic"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/profilePic"
android:id="@+id/UserName"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/email"
android:layout_below="@+id/UserName"
/>

</RelativeLayout>

UserProfile.java

package com.prodevsblog.facebooklogin;

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

import com.squareup.picasso.Picasso;

import org.json.JSONObject;

public class UserProfile extends AppCompatActivity {

JSONObject response, profile_pic_data, profile_pic_url;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
Intent intent = getIntent();
String jsondata = intent.getStringExtra("userProfile");
Log.w("Jsondata", jsondata);
TextView user_name = findViewById(R.id.UserName);
ImageView user_picture = findViewById(R.id.profilePic);
TextView user_email = findViewById(R.id.email);
try {
response = new JSONObject(jsondata);
user_email.setText(response.get("email").toString());
user_name.setText(response.get("name").toString());
profile_pic_data = new JSONObject(response.get("picture").toString());
profile_pic_url = new JSONObject(profile_pic_data.getString("data"));
Picasso.with(this).load(profile_pic_url.getString("url"))
.into(user_picture);

} catch(Exception e){
e.printStackTrace();
}
}
}

LogOut

LoginManager.getInstance().logOut();
NOTE :
To display image, we used Picasso. So you need to add ‘com.squareup.picasso:picasso:2.5.2’ in the dependencies.

See More

Latest Photos