Mobile
Article
By Theodhor Pandeli

Integrating the Facebook API with Android

By Theodhor Pandeli

This article was updated on 13th December, 2016.

In this tutorial, I will show how to connect your Android application to the Facebook API. Lots of mobile applications use the Facebook API v4.x for login, signup and posting data.

Login with Facebook

Profile information

Share to Facebook

Create Android Project

Make sure you have an up to date version of Android Studio. I am using version 1.4.1

Open Android Studio and create a New Project, naming it as you wish. Click Next, choose Minimum API level 17 and click Next again. Choose Empty Activity as the first activity, name it LoginActivity and click Finish.

Next, we add another blank activity to the project. Right Click the package and select New -> Activity -> Blank Activity. Leave its name as default and click finish.

The final project for this article can be found on Github. Make sure you change the Facebook API details to match you own.

Creating Facebook App ID

To use the Facebook API we have to add an app entry to our Facebook Developer Apps dashboard. You will need a Facebook developer account if you don’t have one already. Choose a random category and click Create App ID.

On the next page, scroll down to the bottom and complete both fields with the project packages names.

Package Names

Click Next.

Now we need to add a Development Key Hash. There are two ways of generating one. The first option is using the command line.

Windows

keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl base64

Mac

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

Open Facebook’s My Apps section and copy the App ID:

App ID

Open strings.xml in your project and add this line of code:

<string name="facebook_app_id">{Your App ID here}</string>

Setting up Facebook SDK

Open build.gradle (Project) and add mavenCentral() to both repository sections. Then open build.gradle (Module) and add the SDK library by adding this line to dependencies:

 compile 'com.facebook.android:facebook-android-sdk:4.18.0'

Adding dependencies

Now sync gradle.

Activities and Layouts

Open AndroidManifest.xml and make these changes.

Change the MainActivity label:

<activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/Theme.AppCompat.NoActionBar" >
    </activity>

Add these tags:

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

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

    <provider              android:authorities="com.facebook.app.FacebookContentProvider"                 android:name="com.facebook.FacebookContentProvider"
    android:exported="true"/>

Now we are going to work with Java classes and layouts.

First, we are going to work with LoginActivity.java. This class opens an authenticated connection to the Facebook API and gets data from it.

Add these lines before the onCreate method inside the class:

private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;

//Facebook login button
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {
        Profile profile = Profile.getCurrentProfile();
        nextActivity(profile);
    }
    @Override
    public void onCancel() {        }
    @Override
    public void onError(FacebookException e) {      }
};

Here we create a FacebookCallback called callback. This executes the next action after we get a response from the Facebook API and the method for that is onSuccess().

Inside the onSuccess method we create a new Facebook Profile and get data for that profile. Later we will create a simple function called nextActivity() that will switch our activity.

We are going to initialize the Facebook SDK so we can use its functions and methods. Inside onCreate() add these lines:

FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
    @Override
    protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
    }
};

profileTracker = new ProfileTracker() {
    @Override
    protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
        nextActivity(newProfile);
    }
};
accessTokenTracker.startTracking();
profileTracker.startTracking();

Next, we need to show the famous Facebook Log in button. We don’t need to make it from scratch as it exists inside the SDK’s libraries and can be called in our layout.

So we will edit our LoginActivity’s layout. It’s name should be content_login.xml. In fact, the latest version of Android Studio creates two default .xml files for every activity we create. The other layout file is called activity_login.xml.

In activity_login.xml delete the code for the floating button as we won’t need it.

In content_login.xml there is only a TextView element. We will remove it and create a new LinearLayout that is horizontally oriented. Inside that layout we will add the log in button. Paste the code below to replace the current contents of content_login.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<com.facebook.login.widget.LoginButton
    android:id="@+id/login_button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:gravity="center"
    android:layout_margin="4dp"
    android:paddingTop="12dp"
    android:paddingBottom="12dp"/>

</LinearLayout>

I added some padding at the top and bottom and centered the horizontal linear layout. Let’s return to the Login class and create the button.

Inside the onCreate() method before the closing bracket, add the code below:

LoginButton loginButton = (LoginButton)findViewById(R.id.login_button);
callback = new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {
        AccessToken accessToken = loginResult.getAccessToken();
        Profile profile = Profile.getCurrentProfile();
        nextActivity(profile);
        Toast.makeText(getApplicationContext(), "Logging in...", Toast.LENGTH_SHORT).show();    }

    @Override
    public void onCancel() {
    }

    @Override
    public void onError(FacebookException e) {
    }
};
loginButton.setReadPermissions("user_friends");
loginButton.registerCallback(callbackManager, callback);

Here we create a connection between the button in content_login.xml and the Facebook SDK libraries.

There are some @Overrided methods that we need inside LoginActivity.java. Add the lines below:

@Override
protected void onResume() {
    super.onResume();
    //Facebook login
    Profile profile = Profile.getCurrentProfile();
    nextActivity(profile);
}

@Override
protected void onPause() {

    super.onPause();
}

protected void onStop() {
    super.onStop();
    //Facebook login
    accessTokenTracker.stopTracking();
    profileTracker.stopTracking();
}

@Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
    super.onActivityResult(requestCode, responseCode, intent);
    //Facebook login
    callbackManager.onActivityResult(requestCode, responseCode, intent);

}

The last function in this class is nextActivity() which will switch activities and pass data to the next activity.

private void nextActivity(Profile profile){
    if(profile != null){
        Intent main = new Intent(LoginActivity.this, MainActivity.class);
        main.putExtra("name", profile.getFirstName());
        main.putExtra("surname", profile.getLastName());
        main.putExtra("imageUrl", profile.getProfilePictureUri(200,200).toString());
        startActivity(main);
    }
}

We need the first and last name of the profile and a 200 by 200-pixel profile picture. At this stage, we only get its Uri. These three strings will be used as extras in our next activity.

MainActivity class

The nextActivity() function in the LoginActivity class passed some strings to our next activity. Now we use them by creating three other strings inside the onCreate() method of the MainActivity class and storing the passed data in them:

Bundle inBundle = getIntent().getExtras();
String name = inBundle.get("name").toString();
String surname = inBundle.get("surname").toString();
String imageUrl = inBundle.get("imageUrl").toString();

To display this data we need to change the content_main.xml layout. The code below adds the elements we need to display the data. Add this code inside the RelativeLayout tags:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:text="Hello:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:textSize="20dp"
        android:layout_gravity="center_horizontal"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/nameAndSurname"
        android:textSize="22dp"
        android:textStyle="bold"
        android:layout_marginTop="10dp"
        android:layout_gravity="center_horizontal"/>
    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:id="@+id/profileImage"
        android:layout_marginTop="10dp"
        android:layout_gravity="center_horizontal"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Logout"
        android:id="@+id/logout"/>
</LinearLayout>

To display the profile name add the code below to the onCreate() method of the MainActivity class:

TextView nameView = (TextView)findViewById(R.id.nameAndSurname);
nameView.setText("" + name + " " + surname);

Next, we want to display the profile picture. From the last activity, we have the picture Uri as a string. We can use this Uri to download the picture as a Bitmap file.

Create a new class, and add the code below:

public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImage(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }
}

To display the profile picture in our app, add the line below inside the onCreate() method of the MainActivity class, after the last line added.

new DownloadImage((ImageView)findViewById(R.id.profileImage)).execute(imageUrl);

It uses the imageUrl string, downloads the image and displays it inside the content_main.xml layout.

Now that displaying data is complete, we will add a share dialog to the floating action button so the app can post to Facebook.

Open activity_main.xml and change:

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

to:

android:src="@android:drawable/ic_menu_edit"

Change the button color by editing the color values in colors.xml. I used this color:

<color name="colorAccent">#5694f7</color>

Next to make the button do something.

Declare a private ShareDialog variable in the MainActivity class:

private ShareDialog shareDialog;

Inside the onCreate() method create this dialog:

shareDialog = new ShareDialog(this);

We want to show this dialog when we click the floating button. Replace the Snackbar code in the OnClick method with the code below:

ShareLinkContent content = new ShareLinkContent.Builder().build();
shareDialog.show(content);

Our app can now post to Facebook, but we are not finished yet, the Logout function is missing.

First the app needs to understand if it is logged in. Initialize the Facebook SDK as we did in LoginActivity by adding this line of code inside the onCreate() method:

FacebookSdk.sdkInitialize(getApplicationContext());

Add the logout() function:

Button logout = (Button)findViewById(R.id.logout);
        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LoginManager.getInstance().logOut();
                Intent login = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(login);
                finish();
            }
        });

Now you can run your app and post to Facebook! Please let me know in the comments below if you have any problems or questions.

  • Elio Qoshi

    Very thorough article! No need for full width images though, they are a bit tall this way :)
    Apart that, quite solid!

    • Theodhor Pandeli

      Thank you Elio :). I need to make some changes on my next articles though, image sizes are the first to change :) .

  • I’m a total novice in native mobile development, yet I had no problem following the “recipe”. Good work.

    • Theodhor Pandeli

      Thank you Adrian :)

  • Ivan Bošnjaković

    Your code wont actually work, You need to add permission to manifest file:

    Other than that, just fine :)

    • Chris Ward

      I could have sworn that was in there! Just added, sorry!

  • Mauricio Chavez Vargas

    You have a link to download the project maybe?
    thanks man, is fantastic your code!

  • Vidit Shah

    I am getting error on callbackManager line.
    So please help me..

  • Vidit Shah

    Thanks for help me.. I am solve this problem. But right now getting error like invalid hash key. in regain login process.

  • Madhujit Bhattacharjee

    Very nice tutorial!!! Thanks Theodhor!!!

    • Theodhor Pandeli

      Thank you :)

  • Luca Bondin

    Hi I’m having some trouble with this code as after logging in the app only changes the button to ‘log out’ and no information is displayed on the screen…any help please?

    • CK

      Hi did u solve this problem?? I am facing the same…

      • Dawid Trojanowski

        Anyone Solved it?

        • Theodhor Pandeli

          @lucabondin:disqus @disqus_ag9URG5k1I:disqus @dawidtrojanowski:disqus Hey guys, I just tried the code of this tutorial again and it works perfect, are you sure you have given it the Internet permission in AndroidManifest?

          • Dawid Trojanowski

            finish();
            startActivity(getIntent());

            That solved my problem just by stoping and starting the page.

          • Marcos Junior

            Thanks solved my problem.

          • fdrc

            Where did you put those lines? This works for me on Android 23 but in 16 is not working. Thanks

  • CK

    my login button cannot open main activity

    • Theodhor Pandeli

      Hi, did you check the code? Are all the Facebook SDK methods Okay?

      @Override

      public void onSuccess(LoginResult loginResult) {

      AccessToken accessToken = loginResult.getAccessToken();

      Profile profile = Profile.getCurrentProfile();

      nextActivity(profile);

      Toast.makeText(getApplicationContext(), “Logging in…”, Toast.LENGTH_SHORT).show(); }

      make sure that “nextActivity(profile)” is called inside the onSuccess method :)

      • Theodhor Pandeli

        @lucabondin:disqus is it working now?

        • Dawid Trojanowski

          Nope, i have everything like its on the tutorial and same as u have here in the reply, Still having same error

  • marwa

    Actually when I implemented your code I got errors is that because I have switched between the Activities ? I need the loginActivity to be the main because the facebook button is in the MainActivity.xml

    • Theodhor Pandeli

      Open AndroidManifest.xml and swap the places of “.LoginActivity” with “.MainActivity”

  • Inzimam Tariq

    nextActivity(); function is not working android studio says “can’t resolve method nextActivity(profile);” how to fix that

    • Chris Ward

      @inzimamtariq:disqus Have you added the nexActivity function to LoginActivity?

  • Thanks a lot for this nice tutorial ! It’s really hard to find a good tutorial about the FacebookSDK 4.x. It’s really better than the official get started guide. Good job !

    • Theodhor Pandeli

      Thank you @Arthuriuss:disqus :-)

  • Anas SiDiki

    how can i get the user timeline post .. ?? please help

    • Theodhor Pandeli

      Hello, as you can see that is not covered in this tutorial. To require posts you should use Graph API.

      Thank you and Good luck.

      • Anas SiDiki

        i try graph api code but it not work , kindly if u make another tutorial regarding getting the post or share the code with me , so i will be very thank full to you .

  • Anas SiDiki

    the hrdf parameter is required when click on share button , kindly help

    • Theodhor Pandeli

      What is “hrdf”?

      • Anas SiDiki

        i also dont know first time when i click on share button in works fine , but when i run the app again and click on it its show error and required hrdf parameter ? i stuck in that problem kindly help

  • Showness Malekar

    what to do if we require dateofbirth,gender and other information???

  • Sumedh Bhalerao

    I have a page on Facebook about one football club and there I post information about news, games etc. Now I have made an android app and my question is whether I can fetch the post into the android application ? How can I do it ?

  • Bishnu Dudhraj

    ThanX Theodhor!

    • Theodhor Pandeli

      Thank you @bishnududhraj:disqus :)

  • Really good explained tutorial. Well done Theodhor ;)

    • Theodhor Pandeli

      Thank you @phenrys:disqus :)

  • akhil mb

    getting error on setreadPermission for loginbutton

    • Theodhor Pandeli

      Hello, are you sure you have included this line of code?

      “loginButton.setReadPermissions(“user_friends”);”

      • akhil mb

        yeah bro

  • Rajesh

    its not logging me in on the second time… could any one please help me out from theis problem.

  • taaekon

    hi bro, i have a question how can i hide the button logout when i press the button login?

    • Theodhor Pandeli

      You just need to add “loginButton.setVisibility(View.INVISIBLE)”

      @Override
      public void onSuccess(LoginResult loginResult) {
      Toast.makeText(getApplicationContext(), “Logging in…”, Toast.LENGTH_SHORT).show();
      loginButton.setVisibility(View.INVISIBLE);
      }

  • Ant

    Hi,
    login button cannot open main activity in the first instance.
    So, I say I’m logged in but does not go on the main.
    But if I close the application and then reopen instead lands on the main because it recognizes that they are logged in.

    Debugging in the firts istance, profile = null.
    Because? What do you recommend? Thank you.

  • Aditya

    I’m getting this error

    java.lang.NullPointerException: Attempt to invoke virtual method ‘void com.facebook.login.widget.LoginButton.setReadPermissions(java.lang.String[])’ on a null object reference

    • Theodhor Pandeli

      Hi @disqus_TRVu967PCA:disqus
      Please check this line “LoginButton loginButton = (LoginButton)findViewById(R.id.login_button);”

      Make sure that the Login Button in your XML has the same id as “login_button”

  • Aditya

    getting error loginButton null pointer exception
    loginButton.setReadPermissions(“user_friends”);

    • Theodhor Pandeli

      Hello @disqus_TRVu967PCA:disqus , please make sure you are using the same button ID in your xml, “login_button”:

      LoginButton loginButton = (LoginButton)findViewById(R.id.login_button);

      • Aditya

        Hi Ravi, i have created Gmail and Facebook Login and i fetched data like profile image and email and name to another activity using shared preferences now i need show that data into Tab Activity , i’m confused now where to use shared preferences to display both in Fragments, plzzzzzzz Help soon…

  • Nancy Thakkar

    How we like any feed from app using graph api in android?

  • Hiren Gondaliya

    It will work on Genymotion.
    Not Work on Device.

    • Theodhor Pandeli

      Hello @hirengondaliya:disqus , sorry to hear that.

      Does it show any error on device?

  • Rachit Goyal

    Attempt to invoke virtual method ‘java.lang.Object android.os.Bundle.get(java.lang.String)’ on a null object reference
    on
    String name = inBundle.get(“name”).toString();
    please help

    • Theodhor Pandeli

      Hi @disqus_OHYQuowttZ:disqus , please make sure that you are putting extras before starting the MainActivity activity.

      main.putExtra(“name”, profile.getFirstName());
      main.putExtra(“surname”, profile.getLastName());
      main.putExtra(“imageUrl”, profile.getProfilePictureUri(200,200).toString());

      profile.getFirstName() should not be null.

  • abel rivera

    How can I do it to get the mail, and phone number (if any) of the facebook profile, besides the name and photo I already have?

  • Reinhard Armstrong

    how can i modify the description, add an image, change the tittle?

  • Koti Reddy Gade

    how to get email id of the account?
    please do reply

    • Theodhor Pandeli

      Hello @kotireddygade:disqus

      I am currently writing another article about that, how to get more user data using Graph API Requests. It will be published soon.

      Thanks.

      • Duane

        Is this article ready yet?

  • Ankesh Roy

    Hi,
    login button cannot open main activity in the first instance. I’m logged in but does not go on the main.
    But if I close the application and then reopen instead lands on the main because it recognizes that they are logged in.
    please help me to resolve this problem accept it there is no error in code

  • Waseem Mohamed

    Hi, its really been helpful for me to create Facebook login for my application.
    But, there is a small problem I am facing, I added Facebook login button as on your tutorial,set and logout button in another activity.
    But When I run the app, I can login, After login, a logout button showing the exact place where Facebook login button been place. After few minutes only, that logout button invisible and move to next activity.
    Can you please help on that?

    Android Studio 1.5.1
    Facebook SDK 4.18.0

  • Delfs

    Hello Theodhor, nice tutorial !
    Do you have any tips about how to connect to a site trough webview after the login button is correctly done and the connection with facebook is successful ? I’m having trouble passing the tokens to the webview.. as a consequence, the user can’t connect to the site despite the fact they are already loged in the app.. Thanks in advance!

  • أحمد المغربي

    Snackbar code in the OnClick method
    I can’t find that

  • Kamal Rafiq Baloch

    thanks you so much dear

  • Lunalula

    Great, is there any other version of this tutorial that implements the FB login using Fragments? I want to use it in both my Login and Signup activities

Recommended
Sponsors
Get the latest in Mobile, once a week, for free.