Skip to content

Facebook Login Example

This is an android tutorial to login to your Facebook account and show a Toast message when succesfully logged in.

Obviously you can then later enhance it and do something interesting.

We use simple-fb library as a wrapper around Facebook SDK APIs.

Uses of this Example

No. Major Responsibility
1. Connect to facebook from android.
2. Login to Facebook.
3. Show success, error and failure and see why.

Our Project Source Summary

No. File Major Responsibility
1. MyConfiguration.java Define FaceBook configurations
2. MainActivity.java Provide our application UI and log us in.
3. activity_main.xml Provide template for our MainActivity UI.
4. content_main.xml Allow us to add any view or widget to our UI to be shown in our MainActivity.
5. build.gradle Manage our dependencies including the simple-fb library.

1. Create Basic Activity Project

  1. First create an empty project in android studio. Go to File --> New Project.
  2. Type the application name and choose the company name.
  3. Choose minimum SDK.
  4. Choose Basic activity.
  5. Click Finish.

Basic activity will have a toolbar and floating action button already added in the layout

Normally two layouts get generated with this option:

No. Name Type Description
1. activity_main.xml XML Layout Will get inflated into MainActivity Layout.Typically contains appbarlayout with toolbar.Also has a floatingactionbutton.
2. content_main.xml XML Layout Will be included into activity_main.xml.You add your views and widgets here.
3. MainActivity.java Class Main Activity.

In this example I used a basic activity.

The activity will automatically be registered in the android_manifest.xml. Android Activities are components and normally need to be registered as an application component.

If you've created yours manually then register it inside the <application>...<application> as following, replacing the MainActivity with your activity name:

        <activity android_name=".MainActivity">

            <intent-filter>

                <action android_name="android.intent.action.MAIN" />

                <category android_name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

You can see that one action and category are specified as intent filters. The category makes our MainActivity as launcher activity. Launcher activities get executed first when th android app is run.

Advantage of Creating Basic Activity project

You can optionally choose empty activity over basic activity for this project.

However basic activity has the following advantages:

No. Advantage
1. Provides us a readymade toolbar which gives us actionbar features yet easily customizable
2. Provides us with appbar layout which implements material design appbar concepts.
3. Provides a FloatinActionButton which we can readily use to initiate quick actions especially in examples like these.
4. Decouples our custom content views and widgets from the templating features like toolbar.

Generated Project Structure

AndroidStudio will generate for you a project with default configurations via a set of files and directories.

Here are the most important of them:

No. File Major Responsibility
1. build/ A directory containing resources that have been compiled from the building of application and the classes generated by android tools. Such a tool is the R.java file. R.java file normally holds the references to application resources.
2. libs/ To hold libraries we use in our project.
3. src/main/ To hold the source code of our application.This is the main folder you work with.
4. src/main/java/ Contains our java classes organized as packages.
5. src/main/res/ Contains our project resources folders as follows.
6. src/main/res/drawable/ Contains our drawable resources.
7. src/main/res/layout/ Contains our layout resources.
8. src/main/res/menu/ Contains our menu resources XML code.
9. src/main/res/values/ Contains our values resources XML code.These define sets of name-value pairs and can be strings, styles and colors.
10. AndroidManifest.xml This file gets autogenerated when we create an android project.It will define basic information needed by the android system like application name,package name,permissions,activities,intents etc.
11. build.gradle Gradle Script used to build the android app.

Add Dependencies

Into our app level build.gradle. We add simple-fb library which we use in this project:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'
    compile 'com.sromku:simple-fb:4.1.1'
}

3. Create User Interface

User interfaces are typically created in android using XML layouts as opposed by direct java coding.

This is an example fo declarative programming.

Advantages of Using XML over Java
No. Advantage
1. Declarative creation of widgets and views allows us to use a declarative language XML which makes is easier.
2. It's easily maintanable as the user interface is decoupled from your Java logic.
3. It's easier to share or download code and safely test them before runtime.
4. You can use XML generated tools to generate XML

Here are our layouts for this project:

1. activity_main.xml

  • This layout gets inflated to MainActivity user interface.
  • It includes the content_main.xml.

Here are some of the widgets, views and viewgroups that get employed"

No. View/ViewGroup Package Role
1. CordinatorLayout android.support.design.widget Super-powered framelayout that provides our application's top level decoration and is also specifies interactions and behavioros of all it's children.
2. AppBarLayout android.support.design.widget A LinearLayout child that arranges its children vertically and provides material design app bar concepts like scrolling gestures.
3. ToolBar <android.support.v7.widget A ViewGroup that can provide actionbar features yet still be used within application layouts.
4. FloatingActionButton android.support.design.widget An circular imageview floating above the UI that we can use as buttons.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout

    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_fitsSystemWindows="true"
    tools_context="com.tutorials.hp.facebookstart.MainActivity">

    <android.support.design.widget.AppBarLayout
        android_layout_width="match_parent"
        android_layout_height="wrap_content"
        android_theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android_id="@+id/toolbar"
            android_layout_width="match_parent"
            android_layout_height="?attr/actionBarSize"
            android_background="?attr/colorPrimary"
            app_popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android_id="@+id/fab"
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_layout_gravity="bottom|end"
        android_layout_margin="@dimen/fab_margin"
        android_src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

2. content_main.xml

This layout gets included in your activity_main.xml. You define your UI widgets right here.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout

    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_paddingBottom="@dimen/activity_vertical_margin"
    android_paddingLeft="@dimen/activity_horizontal_margin"
    android_paddingRight="@dimen/activity_horizontal_margin"
    android_paddingTop="@dimen/activity_vertical_margin"
    app_layout_behavior="@string/appbar_scrolling_view_behavior"
    tools_context="com.tutorials.hp.facebookstart.MainActivity"
    tools_showIn="@layout/activity_main">

    <TextView
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_text="Hello World!" />
</RelativeLayout>

4. Java Classes

Here are our java classes:

1. MyConfiguration.java

Our Facebook configuration class. Here's it's responsibilities and how it works:

No. Responsibility Description
1. To maintain an array of facebook permissions allowed for our application. It defines a com.sromku.simple.fb.Permission array. We add the permission of email access since we plan to only login.
2. Maintain a static string containing our facebook app id. Paste your facebook app id in that variable. You need to create an app in your Facebook account before being able to connect an android app to it.
3. Build configuration and return it to the caller. Instantiate the SimpleFacebookConfiguration class and set it's app id, namespace and permissions and build it.
package com.tutorials.hp.facebookstart.mFaceBook;

import com.sromku.simple.fb.Permission;
import com.sromku.simple.fb.SimpleFacebookConfiguration;

public class MyConfiguration {

    Permission[] permissions=new Permission[]{Permission.EMAIL};
    static final String APP_ID="738596112948695";

    public SimpleFacebookConfiguration getMyConfigs()
    {
        SimpleFacebookConfiguration configs=new SimpleFacebookConfiguration.Builder()
                .setAppId(APP_ID)
                .setNamespace("facebookstart")
                .setPermissions(permissions)
                .build();

        return configs;
    }
}

1. MainActivity.java

This is our MainActivity class. The class derives from AppCompatActivity.

No. Responsibility
1. Override the onCreate() method.
2. Inflate the activity_main.xml layout via the setContentView() and set it as the View of our Activity.
3. Reference Toolbar from application layout and set it as the ActionBar.
4. Reference FAB and listen to its onClick events.
5. Instantiate the MyConfiguration class, getMyConfigs() and pass it to setConfiguration() of the SimpleFacebook class.
6. Login when FAB is clicked
package com.tutorials.hp.facebookstart;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.sromku.simple.fb.Permission;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.listeners.OnLoginListener;
import com.sromku.simple.fb.listeners.OnLogoutListener;
import com.tutorials.hp.facebookstart.mFaceBook.MyConfiguration;

import java.util.List;

public class MainActivity extends AppCompatActivity {

   SimpleFacebook fb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

        SimpleFacebook.setConfiguration(new MyConfiguration().getMyConfigs());

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                login();
            }
        });
    }

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

        fb=SimpleFacebook.getInstance(this);
    }

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

        fb.onActivityResult(requestCode,resultCode,data);
    }

    private void login()
    {
        OnLoginListener loginListener=new OnLoginListener() {
            @Override
            public void onLogin(String accessToken, List<Permission> acceptedPermissions, List<Permission> declinedPermissions) {
                Toast.makeText(MainActivity.this,"Logged In",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {
                Toast.makeText(MainActivity.this,"Cancelled ",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onException(Throwable throwable) {
               Log.e("Exception ",throwable.getMessage());
            }
            @Override
            public void onFail(String reason) {
                Log.d("Fail ",reason);
            }
        };
        fb.login(loginListener);
    }
}

5. AndroidManifest.xml

First we need to add permission for internet inside the manifest:

<manifest>
    ....
    <uses-permission android_name="android.permission.INTERNET"/>
    ....
</manifest>

Then add a Facebook activity and meta data inside the component:

<manifest>
<application>
...
    <activity android_name="com.facebook.FacebookActivity"
            android_configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android_theme="@android:style/Theme.Translucent.NoTitleBar"
            android_label="@string/app_name" />

        <meta-data
            android_name="com.facebook.sdk.ApplicationId"
            android_value="@string/app_id" />
...
</application>
</manifest>

And that's it.