Android Facebook SDK Login Integration and Facebook User Profile Display

In this tutorial, we are going to learn how to integrate Facebook SDK for android application login and also we will retrieve and display Facebook user profile information.

There are situations you may want to tell your app users to create account and login before they can make use of your app. It is possible to implement a complete login system for your android app but here we will use Facebook login since almost everybody has Facebook account and the registration process requires just few clicks of button.

If you want to learn how to create a login system in android from scratch, I will recommend you read any of these post I wrote before Android User Login and Registration with Retrofit, Php and MySql or Android Login and Registration with Php and MySql.

To integrate Facebook login in your android application, Facebook account is an essential requirements.

Before we dive into more details, it is important for us to understand what we are planning to achieve. Below is the screen-shot of the application we will be creating.

android facebook login

Lets start to soil our hands in code. Start up your IDE. For this tutorial, I am using the following tools and environment, feel free to use what works for you.

Windows 7

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 23

To create a new android application project, follow the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidFacebookLogin

Package: com.inducesmile.androidfacebooklogin

Select Blank Activity

Name the Activity FacebookActivity

Keep other default selections

Continue to click on the next button until Finish button is active, then click on Finish Button.

Head over to Facebook Developer website to create your app and get your application ID by clicking on the add a new app button as shown below.

Android facebook sdk integration

Select android as your platform from the window pop-up as shown below.

Android facebook sdk integration

Click on create a new app id to see a new dialog window. Fill the details and add your android project package name. Select utilities for the category. Then click create button to create your app.

Android facebook sdk integration

In the next page, you will see details of how to add Facebook SDK to your android project.

The minimum android SDK for this Facebook SDK is API 15.

Add the Maven Central Repository to build.gradle before dependencies:

repositories {

mavenCentral()

}

Add compile ‘com.facebook.android:facebook-android-sdk:[4,5)’ to your build.gradle dependencies and build your project.

Add your Facebook App ID to your app and update your Android manifest.

Open your strings.xml file, for example: /app/src/main/res/values/strings.xml.

Add a new string with the name facebook_app_id containing the value of your Facebook App ID:

<string name=”facebook_app_id”>xxxxxxxxxxxxxx</string>

Open AndroidManifest.xml.

Add a uses-permission element to the manifest:

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

Add a meta-data element to the application element:

<application android:label=”@string/app_name”>

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

</application>

Tell us about your Android project

Add your project package name and the fully qualified class name of the activity that will handle the deep linking.

Add your development and release key hashes

There are different ways to obtain your development key hash and it also depends on the OS platform you are using.

You can read this Stackoverflow.com topic on How to create Android Facebook Key Hash? If you encounter any problem you can use the comment box below to ask question.

Finally, enter the development key hash you obtained in the last text field and click the next button to finish.

Lets start with our project.

Go to the res folder, then double click on the values folder and double click on the colors.xml file and add the following lines of codes. This will holder all the colors we will use in this tutorial.

<color name="colorPrimary">#3F51B5</color>
<?xml version="1.0" encoding="utf-8"?>
<resources> 
<color name="colorPrimary">#3F51B5</color> 
<color name="colorPrimaryDark">#303F9F</color> 
<color name="colorAccent">#FF4081</color> 
<color name="colorPrimaryLight">#7f8fe3</color>
</resources>

Now, head over to the strings.xml file and modify the content with the code below.

<resources> 
<string name="app_name">Android Facebook Login</string> 
<string name="facebook_app_id">xxxxxxxxxxxxxxxxx</string> 
<string name="title_activity_profile">Profile Page</string> 
<string name="navigation_drawer_open">Open navigation drawer</string> <string name="navigation_drawer_close">Close navigation drawer</string> <string name="action_settings">Settings</string> 
<string name="action_logout">Logout</string>
</resources>

We will add Internet permission in our Manifest.xml file. Also, we are going to add a meta-data in the application element.

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

The default FacebookActivity is registered in the Manifest.xml file with the following code

<activity 
android:name="com.facebook.FacebookActivity" 
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation" 
android:label="@string/app_name" 
android:theme="@android:style/Theme.Translucent.NoTitleBar" />

The complete code for Manifest.xml file as as shown

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.inducesmile.androidfacebooklogin"> 
<uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" 
android:label="@string/app_name" 
android:supportsRtl="true" 
android:theme="@style/AppTheme"> 
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id" /> 
<activity android:name=".FacebookActivity" android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation" android:theme="@android:style/Theme.Translucent.NoTitleBar"> 
<intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> 
<activity 
android:name="com.facebook.FacebookActivity" android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation" 
android:label="@string/app_name" android:theme="@android:style/Theme.Translucent.NoTitleBar" /> 
<activity android:name=".ProfileActivity" android:label="@string/title_activity_profile" android:theme="@style/AppTheme.NoActionBar">
</activity> 
</application>
</manifest>

Update the dependencies section of the app build.gradle as shown below

dependencies { 
compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' 
compile 'com.android.support:appcompat-v7:23.2.1' 
compile 'com.facebook.android:facebook-android-sdk:[4,5)' 
compile 'com.android.support:design:23.2.1' 
compile 'com.squareup.picasso:picasso:2.5.2'}

You will see that we will make use of Picasso Library for Network call when downloading and displaying Facebook user profile photo.

activity_facebook.xml

Open the default layout file created by Android Studio when our project is created. Remember that we named it FacebookActivity.java and the corresponding layout file is activity_facebook.xml.

We will add the Facebook LoginButton to our layout file as shown below.

<?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:background="@drawable/loginbg" tools:context="com.inducesmile.androidfacebooklogin.FacebookActivity"> 
<com.facebook.login.widget.LoginButton 
android:id="@+id/login_button" 
android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" />
</RelativeLayout>

 

FacebookActivity.java

In FacebookActivity class, we will initialize the Facebook SDK with this line of code before setting the content view.

FacebookSdk.sdkInitialize(getApplicationContext());

We made the CallbackManager class a class member variable and instantiate it in onCreate(Bundle savedInstanceState) method.

public class FacebookActivity extends Activity { private CallbackManager mCallbackManager;

There are two ways to add Facebook login button –

LoginManager – Initiates the login process with the requested read or publish permissions.

LoginButton – This UI element wraps functionality available in the LoginManager. So when someone clicks on the button, the login is initiated with the set permissions. The button follows the login state, and displays the correct text based on someone’s authentication state.

We are going to use the LoginButton in this tutorial.

We will get the instance of the LoginButton with findViewById(int id) method of the activity class. The register the CallbackManager object to our loginButton.

LoginButton mLoginButton = (LoginButton)findViewById(R.id.login_button);mLoginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() { 
@Override public void onSuccess(LoginResult loginResult) { } 
@Override public void onCancel() { } @Override public void onError(FacebookException error) { }});

If the login is successful, the loginResult object will contain information about the authenticated user.

We will use the Profile class to get Facebook public information of the login user. Finally, we will use an intent to pass this information to the next activity class.

The complete code for FacebookActivity class is as shown below.

import android.app.Activity;import android.content.Intent;
import android.os.Bundle;import com.facebook.CallbackManager;import com.facebook.FacebookCallback;
import com.facebook.FacebookException;import com.facebook.FacebookSdk;import com.facebook.Profile;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

public class FacebookActivity extends Activity { 
private CallbackManager mCallbackManager; 
public static final String PROFILE_USER_ID = "USER_ID"; 
public static final String PROFILE_FIRST_NAME = "PROFILE_FIRST_NAME"; public static final String PROFILE_LAST_NAME = "PROFILE_LAST_NAME"; public static final String PROFILE_IMAGE_URL = "PROFILE_IMAGE_URL"; 

@Override
 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FacebookSdk.sdkInitialize(getApplicationContext()); setContentView(R.layout.activity_facebook); mCallbackManager = CallbackManager.Factory.create(); LoginButton mLoginButton = (LoginButton)findViewById(R.id.login_button); 

mLoginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() { 
@Override 
public void onSuccess(LoginResult loginResult) { 
String userLoginId = loginResult.getAccessToken().getUserId(); 
Intent facebookIntent = new Intent(FacebookActivity.this, ProfileActivity.class); 
Profile mProfile = Profile.getCurrentProfile(); 
String firstName = mProfile.getFirstName(); 
String lastName = mProfile.getLastName(); 
String userId = mProfile.getId().toString(); 
String profileImageUrl = mProfile.getProfilePictureUri(96, 96).toString(); 

facebookIntent.putExtra(PROFILE_USER_ID, userId); facebookIntent.putExtra(PROFILE_FIRST_NAME, firstName); facebookIntent.putExtra(PROFILE_LAST_NAME, lastName); facebookIntent.putExtra(PROFILE_IMAGE_URL, profileImageUrl); 
startActivity(facebookIntent);

 } 

@Override 
public void onCancel() { } 

@Override
public void onError(FacebookException error) { }

 }); 
} 

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

); 

mCallbackManager.onActivityResult(requestCode, resultCode, data); 

} 

@Override 
protected void onResume() { 
super.onResume(); 

AppEventsLogger.activateApp(this);

 } 

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

}

 

ProfileActivity Page

We will create a profile activity page which is the page a user will land immediately the user login into the app.

We are going to display the user Facebook profile photo, id, first and last name. To best illustrate it, we are going to use a navigation drawer and the header of the drawer will holder user profile information.

Following the same process of creating new activity to create a new activity file and name it ProfileActivity.java.

The only thing we are going to do is to get all the information we passed to ProfileActivity class through intent then we will get the instance of the view controls in our navigation drawer and we will set the retrieved intent data to the instances of the widgets.

The complete code for the ProfileActivity class is as shown below.

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginManager;
import com.squareup.picasso.Picasso;

public class ProfileActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { 

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); 

FacebookSdk.sdkInitialize(getApplicationContext()); setContentView(R.layout.activity_profile); 
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); 
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
assert drawer != null; 
drawer.setDrawerListener(toggle); 

toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); 
assert navigationView != null; View headerLayout = navigationView.getHeaderView(0); 
navigationView.setNavigationItemSelectedListener(this); 

ImageView profileView = (ImageView)headerLayout.findViewById(R.id.profile_image); 
TextView profileName = (TextView)headerLayout.findViewById(R.id.profile_name); 
TextView profileUserId = (TextView)headerLayout.findViewById(R.id.profile_user_id); 
String profileUserID = returnValueFromBundles(FacebookActivity.PROFILE_USER_ID); 
String profileFirstName = returnValueFromBundles(FacebookActivity.PROFILE_FIRST_NAME); 
String profileLastName = returnValueFromBundles(FacebookActivity.PROFILE_LAST_NAME); 
String profileImageLink = returnValueFromBundles(FacebookActivity.PROFILE_IMAGE_URL); profileName.setText(profileFirstName + " " + profileLastName); profileUserId.setText("User ID : " + profileUserID); 

Picasso.with(ProfileActivity.this).load(profileImageLink).into(profileView); 

} 

@Override 
public void onBackPressed() { 
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); assert drawer != null; 
if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); 
} else { 
super.onBackPressed(); 
}
}

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.profile, menu); 
return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
// Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. 

int id = item.getItemId(); 
//noinspection SimplifiableIfStatement 
if (id == R.id.action_logout) { 
LoginManager.getInstance().logOut(); 
Intent logoutIntent = new Intent(ProfileActivity.this, FacebookActivity.class); startActivity(logoutIntent); 
finish(); 
return true; 
} 
return super.onOptionsItemSelected(item); 

}

@SuppressWarnings("StatementWithEmptyBody") 
@Override 
public boolean onNavigationItemSelected(MenuItem item) { 
// Handle navigation view item clicks here. 
int id = item.getItemId(); 
if (id == R.id.nav_camera) { 
// Handle the camera action 
} else if (id == R.id.nav_gallery) { 
} else if (id == R.id.nav_slideshow) { 
} else if (id == R.id.nav_manage) { 
} else if (id == R.id.nav_share) { 
} else if (id == R.id.nav_send) { 
} 

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; 
}

private String returnValueFromBundles(String key){ 
Bundle inBundle = getIntent().getExtras(); 
String returnedValue = inBundle.get(key).toString(); 
return returnedValue; 
}
}

One final thing we will do is to implement the logout function as a menu action view. We will modify the default menu layout file as shown

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> 
<item android:id="@+id/action_logout" 
android:orderInCategory="100" 
android:title="@string/action_logout" 
app:showAsAction="never" />
</menu>

In onOptionsItemSelected(MenuItem item) method, when the action view is selected, we will call the logout function as shown

if (id == R.id.action_logout) { 
LoginManager.getInstance().logOut(); 
Intent logoutIntent = new Intent(ProfileActivity.this, FacebookActivity.class); startActivity(logoutIntent); 
finish(); 
return true;
}

You can also request for extra permission if you are interested in getting Facebook non-user public information. You can read more about this Facebook for developers page 

I have a complete Android login source codes with advance features and admin back-end with user login details that comprises of Android Facebook Login, Android Twitter Login, Android Google Plus Login, Android Login and Registration with Php and MySql, Android Login with Firebase. It sells for $5.

Kindly contact me if you need it. I offer 24 – 7 support for smooth integration in your application.

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

Remember to subscribe with your email address so that you will be among the first to receive my new post once it is published.

Please if you love this tutorial, kindly download my android app – Complete Mathematics – in Google Play Store and let me know what you think about it.

OTHER INTERESTING POSTS:

4 Comments

    • Henry

Add a Comment