Android Programming

Android Facebook - Simple Login.

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. Define FaceBook configurations
2. 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. New Project Dialog

  3. Choose minimum SDK. Choose minimum SDK

  4. Choose Basic activity. Choose Empty Activity

  5. Click Finish. 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. 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">


                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />



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 file. 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 ''
    compile ''
    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 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 A LinearLayout child that arranges its children vertically and provides material design app bar concepts like scrolling gestures.
3. ToolBar < A ViewGroup that can provide actionbar features yet still be used within application layouts.
4. FloatingActionButton An circular imageview floating above the UI that we can use as buttons.
<?xml version="1.0" encoding="utf-8"?>
< xmlns:android=""


            app:popupTheme="@style/AppTheme.PopupOverlay" />


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

        android:src="@android:drawable/ic_dialog_email" />


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 xmlns:android=""

        android:text="Hello World!" />

4. Java Classes

Here are our java classes:


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()

        return configs;


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.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;

    protected void onCreate(Bundle savedInstanceState) {
        Toolbar toolbar = (Toolbar) findViewById(;
        FloatingActionButton fab = (FloatingActionButton) findViewById(;

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

        fab.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

    protected void onResume() {


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


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

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

            public void onException(Throwable throwable) {
               Log.e("Exception ",throwable.getMessage());
            public void onFail(String reason) {
                Log.d("Fail ",reason);

5. AndroidManifest.xml

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

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

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

    <activity android:name="com.facebook.FacebookActivity"
            android:label="@string/app_name" />

            android:value="@string/app_id" />

And that's it.