Android Facebook login implementation with Fragment

In this post, I am going to discuss about integrating Facebook login in Android applications using Facebook SDK.

In the previous post – How to implement Facebook login in Android applications?, I walked you through how to implement Facebook login using Activity but in this post I am going to discuss about implementing it with Android Fragment.

What is Facebook SDK?

Facebook provides SDK for Android to build Android applications to increase the engagement with it’s World’s number one Social Networking platform. To know more about Facebook SDK, please follow this link.

What are we going to develop?

The application which we are going to develop will ask you to login with Facebook account on click of “Facebook Login” button. On successful login, your basic details like Firstname, Lastname, Location, Gender etc., will be retrieved and displayed inside the application.

You can download source code from here if you don’t want to create Application from scratch, otherwise please proceed with below listings.

Prerequisites

Facebook SDK must be configured in your Eclipse IDE, please take help from this post – Getting Started with the Facebook SDK for Android to setup Facebook SDK.

Let us start with creating Android application.

Step 1: Create Android Application Project

  • Create new android project [File >> New >> Android Application Project] with project name FBFragmentLoginActivity
  • Enter the package name and activity name you have entered in Facebook developer console while creating Facebook Application
  • Choose Minimum Required SDK, Target SDK and Compile with (Choose latest SDKs to make sure Facebook SDK will work without any issues). Confused on choosing these options? Take a look at Minimum Required SDK – Target SDK – Compile With post.
  • Click Next button and finally click ‘Finish’ to create project

Step 2: Add Facebook SDK as dependency project

Right click on the project you created >> Choose Properties >> Choose Android Tab >> Go to lower part of the dialog >> Click on Add button >> Select FacebookSDK Project.

Troubleshooting Tips:

  1. You should configure FacebookSDK in your workspace, that means import FacebookSDK library project into your workspace before your try to add it as dependency project.
  2. FacebookSDK library project and the Anroid application you just created should be under same Workspace.

Step 3: Create color xml and gradient XML

Create colors.xml under res/values:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="white">#ffffff</color>
    <color name="black">#000000</color>
    <color name="bg_gradient_start">#EB5038</color>
    <color name="bg_gradient_end">#CA3822</color>
    <color name="bg_button_login">#A92815</color>
</resources>

Create bg_gradient.xml under res/drawable-mdpi:

<?xml version="1.0" encoding="UTF-8"?>
<shape 
    xmlns:android="http://schemas.android.com/apk/res/android"  android:shape="rectangle" >
    <gradient
        android:gradientRadius="750"
        android:endColor="@color/bg_gradient_end"
        android:startColor="@color/bg_gradient_start"
        android:type="radial" />
</shape>

Add below image (Right Click >> Save as) under res/drawable-mdpi:

myapp_bg_image

Step 4: Design screen

Open activity_main.xml and replace it with below code.

<LinearLayout 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/bg_gradient"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.prgguru.example.MainActivity" >

    <ImageView
        android:layout_width="300dp"
        android:layout_height="100dp"
        android:layout_gravity="center"
        android:src="@drawable/myapp_bg_image" />

    <LinearLayout
        android:id="@+id/other_views"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical"
        android:padding="5dp" >

        <TextView
            android:id="@+id/name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:gravity="left"
            android:text="Name"
            android:textColor="@color/white"
            android:textSize="30dp" />

        <TextView
            android:id="@+id/gender"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:gravity="left"
            android:text="Gender"
            android:textColor="@color/white"
            android:textSize="15dp" />

        <TextView
            android:id="@+id/location"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:gravity="left"
            android:text="Location"
            android:textColor="@color/white"
            android:textSize="15dp" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/fb_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="bottom"
        android:orientation="vertical"
        android:padding="5dp" >

        <com.facebook.widget.LoginButton
            android:id="@+id/authButton"
            android:layout_width="250dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="30dp" />
    </LinearLayout>

</LinearLayout>

Step 5: MainActivity.java – Main Class and MainFragment.java – Fragment Class

Open MainActivity.java and replace it with below code.

Each line of code is commented well, if you still have any doubt or question discuss it.

package com.prgguru.example;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class MainActivity extends FragmentActivity {
	private MainFragment mainFragment;

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

		if (savedInstanceState == null) {
			// Add the fragment on initial activity setup
			mainFragment = new MainFragment();
			getSupportFragmentManager().beginTransaction()
					.add(android.R.id.content, mainFragment).commit();
		} else {
			// Or set the fragment from restored state info
			mainFragment = (MainFragment) getSupportFragmentManager()
					.findFragmentById(android.R.id.content);
		}
	}

 
}

Create MainFragment.java under the package you created and add below code into it:

package com.prgguru.example;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;

public class MainFragment extends Fragment {
	private static final String TAG = "MainFragment";
	// Create, automatically open (if applicable), save, and restore the 
	// Active Session in a way that is similar to Android UI lifecycles. 
	private UiLifecycleHelper uiHelper;
	private View otherView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// To maintain FB Login session
		uiHelper = new UiLifecycleHelper(getActivity(), callback);
		uiHelper.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.activity_main, container, false);
		// Looks for Login button
		LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
		authButton.setFragment(this);
		// Set View that should be visible after log-in invisible initially
		otherView = view.findViewById(R.id.other_views);
		otherView.setVisibility(View.GONE);
		//authButton.setReadPermissions(Arrays.asList("user_likes", "user_status","email","user_birthday"));
		return view;
	}
	
	// Called when session changes
	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};

	// When session is changed, this method is called from callback method
	private void onSessionStateChange(Session session, SessionState state,
			Exception exception) {
		final TextView name = (TextView) getView().findViewById(R.id.name);
		final TextView gender = (TextView) getView().findViewById(R.id.gender);
		final TextView location	= (TextView) getView().findViewById(R.id.location);
		
		if (state.isOpened()) {
			Log.i(TAG, "Logged in...");
			// make request to the /me API to get Graph user
			Request.newMeRequest(session, new Request.GraphUserCallback() {

				// callback after Graph API response with user
				// object
				@Override
				public void onCompleted(GraphUser user, Response response) {
					if (user != null) {
						// Set view visibility to true
						otherView.setVisibility(View.VISIBLE);
						// Set User name 
						name.setText("Hello " + user.getName());
						// Set Gender
						gender.setText("Your Gender: "
								+ user.getProperty("gender").toString());
						location.setText("Your Current Location: "
								+ user.getLocation().getProperty("name")
										.toString());
					}
				}
			}).executeAsync();
		} else if (state.isClosed()) {
			Log.i(TAG, "Logged out...");
			otherView.setVisibility(View.GONE);
		}
	}

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

		uiHelper.onActivityResult(requestCode, resultCode, data);
		Log.i(TAG, "OnActivityResult...");
	}

	@Override
	public void onResume() {
		super.onResume();
		uiHelper.onResume();
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		uiHelper.onSaveInstanceState(outState);
	}
}

Step 6: Add the Facebook app ID into your project

Add your Facebook app ID into your project, open up the strings.xml file in the res/values folder of your project and add below value:

<string name="app_id">YOUR_FACEBOOK_APP_ID</string>

Step 7: Add Meta Data to application tag in AndroidManifest

As shown below, add a ‘Meta Data’ item called com.facebook.sdk.ApplicationId, with a value of the app_id string you just configured:

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

Step 8: Add permission in AndroidManifest.xml

Add Internet permission in AndroidManifest:

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

Step 9: Add Facebook Login Activity in AndroidManifest.xml

  <activity
            android:name="com.facebook.LoginActivity"
            android:theme="@style/AppTheme" >
        </activity>

[pglinkadssmall1]

Here is the complete AndroidManifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.prgguru.example"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.INTERNET" />
, 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/app_id" />

        <activity
            android:name="com.prgguru.example.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.facebook.LoginActivity"
            android:theme="@style/AppTheme" >
        </activity>
    </application>

</manifest>

Demo

That’s all. It’s time to test our code.

Run the application using emulator or device by right clicking on the project >> Run as >> Android applicaiton >> Choose emulator or device.



Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project (How to import android project in eclipse).

Download Source Code

*apk in Android  is the installation file similar to exe in windows.

[pglinkadssmall]

If you feel this article is helpful and interesting please spread a word about it to your friends and colleagues by sharing the article in Facebook or Twitter.

Share

You are always welcome to provide your comments and feedback from comment box.

[pgwriteforus]

[pgfeedback]

Related Articles

Author: Android Guru

Share This Post On
Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest

Shares