Android - Facebook Integration Sample: Login and get User Profile

    Social media integration is one of the most popular topics that we can see in applications programming. Like another social networks, Facebook provides powerful API for a lot of platform, including mobiles OS in general and Android in particular. As we can see in many applications which needing user dentifiable information (account),  they allow us to create a new account from Facebook ID (Login with Facebook). By this way, apps will use oAuth to get our public information through connecting and communicating with Facebook SDK.
    Through this post, I would like to present a sample project that by login with your Facebook account process, user can get the profile information responding in Graph API and show data to views.
    DEMO VIDEO:

Register your app


    All apps that use the Facebook SDK must be registered with Facebook. Log in to the Facebook Developers website and click Create a New App in the top right corner. With some simple steps, enter your new app name, select category, platform (Android), app's package name and launching Activity name..., make sure you remember the values you entered.
    Key hashes field will be opened and we must fill it. Launch Terminal (in Mac, Linux) or Command Prompt (in Windows) and type this command:
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64
    After enter password for Android debug.keystore (default is android), a key hash has been generated:
    Copy and paste it to App register form, make sure Single Sign On is set to Yes and click the Save Changes button. Your app is now registered:
    And our app dashboard will be like this:

Add Facebook SDK to Project

  The Facebook SDK is available on Maven Central. In order to use it, open app/build.gradle and add this dependency (the lastest version of sdk in this article time is 4.7.0):
compile 'com.facebook.android:facebook-android-sdk:4.7.0'

Add the Application ID

    As you can see above, each created app has a it's own ID and we must declared it in Android project. So, open strings resource file (strings.xml) and add app id value:     We need do something in AndroidManifest.xml. First, adding application ID meta-data just above </application> tag:     Define FacebookActivity as another Activity that belongs to our app:     And set Internet permission for app:

Designing project layout

    In project main activity, I put a LoginButton object to connect with a Facebook account after click and after this process, user profile will be get and show to TextView, specially, user profile picture will be show by ProfilePictureView. Our layout file like this:

Programmatically coding


    The SDK needs to be initialized before using any of its methods. You can do so by calling sdkInitialize() method and passing the application's context to it. Put this line in Activity onCreate():
FacebookSdk.sdkInitialize(getApplicationContext());
    After that, initialize an instance of CallbackManager using the CallbackManager.Factory.create() method:
callbackManager = CallbackManager.Factory.create();
    Now, set a call back to handle results of the login attempts, register it with CallbackManager instance above. Implements FacebookCallBack interface, we have ButtonLogin registerCallback:
        btnLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {

            @Override
            public void onSuccess(LoginResult loginResult) {
                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        new GraphRequest.GraphJSONObjectCallback() {

                            @Override
                            public void onCompleted(JSONObject object, GraphResponse response) {
                                Log.v("Main", response.toString());
                                setProfileToView(object);
                            }
                        });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email,gender, birthday");
                request.setParameters(parameters);
                request.executeAsync();
            }

            @Override
            public void onCancel() {
                // App code
            }

            @Override
            public void onError(FacebookException exception) {
                Toast.makeText(MainActivity.this, "error to Login Facebook", Toast.LENGTH_SHORT).show();
            }
        });
    The responding data is in JSONObject, parsing it based on key name and set to views:
private void setProfileToView(JSONObject jsonObject) {
        try {
            email.setText(jsonObject.getString("email"));
            gender.setText(jsonObject.getString("gender"));
            facebookName.setText(jsonObject.getString("name"));

            profilePictureView.setPresetSize(ProfilePictureView.NORMAL);
            profilePictureView.setProfileId(jsonObject.getString("id"));
            infoLayout.setVisibility(View.VISIBLE);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    Overriding onActivityResult() to get data in CallbackManager:
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }
    Finally, we have full code for main Activity:
package info.devexchanges.facebookintegration;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.facebook.login.widget.ProfilePictureView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    private LoginButton btnLogin;
    private CallbackManager callbackManager;
    private ProfilePictureView profilePictureView;
    private LinearLayout infoLayout;
    private TextView email;
    private TextView gender;
    private TextView facebookName;

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

        setContentView(R.layout.activity_main);

        btnLogin = (LoginButton)findViewById(R.id.login_button);
        email = (TextView)findViewById(R.id.email);
        facebookName = (TextView)findViewById(R.id.name);
        gender = (TextView)findViewById(R.id.gender);
        infoLayout = (LinearLayout)findViewById(R.id.layout_info);
        profilePictureView = (ProfilePictureView)findViewById(R.id.image);

        btnLogin.setReadPermissions(Arrays.asList("public_profile, email, user_birthday"));
        callbackManager = CallbackManager.Factory.create();

        // Callback registration
        btnLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {

            @Override
            public void onSuccess(LoginResult loginResult) {
                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        new GraphRequest.GraphJSONObjectCallback() {

                            @Override
                            public void onCompleted(JSONObject object, GraphResponse response) {
                                Log.v("Main", response.toString());
                                setProfileToView(object);
                            }
                        });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email,gender, birthday");
                request.setParameters(parameters);
                request.executeAsync();
            }

            @Override
            public void onCancel() {
                
            }

            @Override
            public void onError(FacebookException exception) {
                Toast.makeText(MainActivity.this, "error to Login Facebook", Toast.LENGTH_SHORT).show();
            }
        });
    }

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

    private void setProfileToView(JSONObject jsonObject) {
        try {
            email.setText(jsonObject.getString("email"));
            gender.setText(jsonObject.getString("gender"));
            facebookName.setText(jsonObject.getString("name"));

            profilePictureView.setPresetSize(ProfilePictureView.NORMAL);
            profilePictureView.setProfileId(jsonObject.getString("id"));
            infoLayout.setVisibility(View.VISIBLE);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
    Our result after login Facebook and fetching data:

Conclusions

    Through this post, I presented a simple solution to login and get user information from a Facebook account. For further approach, you can go to Facebook Developer site to read more about Android SDK to deep understanding it. By this, you can find out the way to fetch not only user profile but also get the friends list or posting status, sharing link,...to your Facebook wall. Hope you like this topic, finally, you can see my project on @Github and check this link to read about integration Google+, Twitter and Google Play services,...in your Android app.


Share


Previous post
« Prev Post
Next post
Next Post »