Android Facebook Integration

By | December 1, 2015

In this tutorial we will see how to integrate facebook into your application by using latest version of Facebook’s SDK for Android , Facebook SDK for Android makes it easier and faster to integrate. here in this tutorial we will see how to add facebook login feature to your application , login provides a convenient and secure way for people to log in to an app without having to go through a sign-up process and we will also see how to extract the user information from logged_in user and show on the UI .

androidfacebooksdk

Also Read :

Android Twitter Oauth Login using Fabric .
Andoid Twitter Integration using Twitter4j.

Generate Facebook Hash Key

To Register the your Facebook App you must create a hash key from below command

To make the below command to work you must download the OpenSSL from here and set the environment variable for it.

copy the hash key which we will be using while registering facebook app.

Command

keytool -exportcert -alias androiddebugkey -keystore “%USERPROFILE%.androiddebug.keystore | openssl sha1 -binary | openssl base64

Example

keytool -exportcert -alias androiddebugkey -keystore C:Userspawan.androiddebug.keystore | openssl sha1 -binary | openssl base64

Android Generating Sha1 Key

Create Facebook App

To Create the facebook app go to ( https://developers.facebook.com/apps ) and the just follow the below steps.

androidfacebookapp_01

androidfacebookapp_02

androidfacebookapp_03

androidfacebookapp_04

androidfacebookapp_05

After Creating Facebook app register by filling information like package name , class name and hash key .

androidfacebookapp_06

Build Gradle

Open build.gradle(app:module) , add the repository first, and then the dependency which includes Facebook SDK and Picasso (Picasso lib is used to load image from url) .

file : build.gradle

dependencies {
 compile fileTree(dir: 'libs', include: ['*.jar'])
 compile 'com.android.support:appcompat-v7:23.1.0'
 compile 'com.facebook.android:facebook-android-sdk:4.7.0'
 compile "com.squareup.picasso:picasso:2.4.0"
}

String Constant

Open res/value/strings.xml and modify as below . make sure to add your app id .

file : strings.xml

<resources>
    <string name="app_name">AndroidFacebook</string>
    <string name="facebook_app_id">Your_App_ID</string>
</resources>

Android Manifest

Add Internet Permission and meta tag inside the Android Manifest file

file : AndroidManifest.xml

<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tutorialsbuzz.androidfacebook">

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

    <application
        android:theme="@style/AppTheme"
    ......................
    >

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

    .........
    .......

   </application>
    
</manifest>

XML Layout

Create a layout file activity_main.xml inside res/layout and modify as below .

file : activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/fragment"
        android:name="com.tutorialsbuzz.androidfacebook.LoginFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout="@layout/login_fragment" />

</RelativeLayout>

Create a layout file login_fragment.xml inside res/layout and modify as below this layout file contain custom login button from facebook sdk .

file : login_fragment.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:id="@+id/parentLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

</RelativeLayout>

Create a layout file home_fragment.xml inside res/layout and modify as below this layout file contains textView and ImageView .

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp">

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:textSize="32sp" />

    <ImageView
        android:id="@+id/profile_pic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tv_name"
        android:layout_centerHorizontal="true"
        android:src="@mipmap/ic_launcher" />

    <Button
        android:id="@+id/logout_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/profile_pic"
        android:layout_marginTop="10dp"
        android:text="Log out" />

</RelativeLayout>

Activity

Create a class AndroidFacebookActivity and initialize Facebook SDK inside the onCreatView before setContentView

file : AndroidFacebookActivity.java

package com.tutorialsbuzz.androidfacebook;

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

import com.facebook.FacebookSdk;

public class AndroidFacebookActivity extends AppCompatActivity {

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

        FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.activity_main);
    }
}

Login Fragment

  • Create a class LoginFragment and inside the onViewCreated method register for click event for login button.
  • Call registerCallback method on loginbutton instance as you can see the registerCallback method takes two parameter callbackManager and callback.
  • Override the onActvityResult() method and inside method make a call to onActvityResult() method on callback instance.
  • Create an Instance of FacebookCallBack and override the onSuccess , onError and onCancel method , inside the onSuccess method we will make call to a homeFragment() , this method will redirects to home fragment .

file : LoginFragment.java

package com.tutorialsbuzz.androidfacebook;

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

import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

public class LoginFragment extends Fragment {

    private CallbackManager callbackManager = null;
    private AccessTokenTracker mtracker = null;
    private ProfileTracker mprofileTracker = null;

    public static final String PARCEL_KEY = "parcel_key";

    private LoginButton loginButton;

    FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {

            Profile profile = Profile.getCurrentProfile();
            homeFragment(profile);
        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {

        }
    };

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

        callbackManager = CallbackManager.Factory.create();


        mtracker = new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {

                Log.v("AccessTokenTracker", "oldAccessToken=" + oldAccessToken + "||" + "CurrentAccessToken" + currentAccessToken);
            }
        };


        mprofileTracker = new ProfileTracker() {
            @Override
            protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {

                Log.v("Session Tracker", "oldProfile=" + oldProfile + "||" + "currentProfile" + currentProfile);
                homeFragment(currentProfile);

            }
        };

        mtracker.startTracking();
        mprofileTracker.startTracking();
    }


    private void homeFragment(Profile profile) {

        if (profile != null) {
            Bundle mBundle = new Bundle();
            mBundle.putParcelable(PARCEL_KEY, profile);
            HomeFragment hf = new HomeFragment();
            hf.setArguments(mBundle);

            FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager
                    .beginTransaction();
            fragmentTransaction.replace(R.id.mainContainer, new HomeFragment());
            fragmentTransaction.commit();
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.login_fragment, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        loginButton = (LoginButton) view.findViewById(R.id.login_button);
        loginButton.setReadPermissions("user_friends");
        // If using in a fragment
        loginButton.setFragment(this);
        loginButton.registerCallback(callbackManager, callback);
    }

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

    @Override
    public void onStop() {
        super.onStop();
        mtracker.stopTracking();
        mprofileTracker.stopTracking();
    }


    public boolean isLoggedIn() {
        AccessToken accessToken = AccessToken.getCurrentAccessToken();
        return accessToken != null;
    }

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

        if (isLoggedIn()) {
            loginButton.setVisibility(View.INVISIBLE);
            Profile profile = Profile.getCurrentProfile();
            homeFragment(profile);
        }

    }
}

Home Fragment

User Will land into home fragment on successful login , here in this fragment we will show user info on UI .

Create HomeFragment class and inside the onActivityCreated() we will get the instance of Profile class which contains user information , which you can show on UI .

file : HomeFragment.java

package com.tutorialsbuzz.androidfacebook;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.Profile;
import com.facebook.login.LoginManager;
import com.squareup.picasso.Picasso;

public class HomeFragment extends Fragment {

    private ImageView profile_pic = null;
    private TextView tv = null;
    private Button logoutButton = null;
    private Profile profile = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.home_fragment, container, false);
        profile_pic = (ImageView) view.findViewById(R.id.profile_pic);
        tv = (TextView) view.findViewById(R.id.tv_name);
        logoutButton = (Button) view.findViewById(R.id.logout_button);
        return view;
    }


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

        Bundle bundle = getArguments();

        if (bundle != null) {
            profile = (Profile) bundle.getParcelable(LoginFragment.PARCEL_KEY);
        } else {
            profile = Profile.getCurrentProfile();
        }


        tv.setText("Welcome \n" + profile.getName());

        Picasso.with(getActivity())
                .load(profile.getProfilePictureUri(400, 400).toString())
                .into(profile_pic);

        logoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logout();
            }
        });

    }

    private void logout() {
        LoginManager.getInstance().logOut();
        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        fragmentTransaction.replace(R.id.mainContainer, new LoginFragment());
        fragmentTransaction.commit();
    }

}

androidfacebook

androidfacebooklogin

androidfacebookuserprofile

 

 

  • This comment has been removed by the author.

  • Hu, when I run the application it gives me an error
    and said
    Unfortunately, FacebookAppplication has stopped
    I debug and knew that the problem is in activity main ..

    my activity_main.xml is

    please anyone help me thanks a lot
    Ayman

  • can you share the logcat

  • at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
    Caused by: The SDK has not been initialized, make sure to call FacebookSdk.sdkInitialize() first.
    at com.facebook.internal.Validate.sdkInitialized(Validate.java:145)
    at com.facebook.AccessTokenTracker.(AccessTokenTracker.java:55)
    at com.example.ayman.facebookapplication.LoginFragment$2.(LoginFragment.java:58)
    at com.example.ayman.facebookapplication.LoginFragment.onCreate(LoginFragment.java:58)
    at android.support.v4.app.Fragment.performCreate(Fragment.java:1951)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1029)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1230)
    at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1332)
    at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2288)
    at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
    at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:357)
    at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:31)
    at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:80)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:754)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704) 
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:835) 

  • Make Sure In AndroidFacebookActivity you have made call to
    "FacebookSdk.sdkInitialize(getApplicationContext());"
    and then call setContentView