Sunday, April 24, 2016

android - Facebook sdk graph api to get user data

activity_main.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: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"
    tools:context="com.example.cfsuman.androidfacebooksdktutorials.MainActivity"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="italic"
        android:fontFamily="sans-serif-condensed"
        android:textColor="#2b55d2"
        />
    <TextView
        android:id="@+id/tv_info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv"
        />
    <com.facebook.login.widget.LoginButton
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="30dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        />
</RelativeLayout>
MainActivity.java

package com.example.cfsuman.androidfacebooksdktutorials;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

// For facebook sdk
import com.facebook.AccessToken;
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.appevents.AppEventsLogger;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

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


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Activity mActivity;

    private TextView mTextView;
    private TextView mTVInfo;

    // For facebook sdk
    private CallbackManager mCallbackManager;
    private LoginButton mLoginButton;

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

        // Initialize the facebook sdk
        FacebookSdk.sdkInitialize(getApplicationContext());
        mCallbackManager = CallbackManager.Factory.create();

        // Set the content view
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();
        mActivity = MainActivity.this;

        // Get the widgets reference from XML layout
        mTextView = (TextView)findViewById(R.id.tv);
        mTVInfo = (TextView)findViewById(R.id.tv_info);

        // For facebook sdk
        mLoginButton = (LoginButton)findViewById(R.id.login_button);
        mLoginButton.setReadPermissions("email");

        // Check if the user already logged in
        if(AccessToken.getCurrentAccessToken()!=null){
            sendGraphRequest(AccessToken.getCurrentAccessToken());
            Toast.makeText(mContext,"Already logged in",Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(mContext,"User not logged in",Toast.LENGTH_SHORT).show();
        }

        // For facebook sdk
        // Callback registration for facebook login button
        mLoginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>(){
            @Override
            public void onSuccess(LoginResult loginResult){
                // App code
                // Display the login info in TextView
                mTextView.setText("User ID: " + loginResult.getAccessToken().getUserId());
                mTextView.setText(mTextView.getText() + "\n\nAccess Token: " + loginResult.getAccessToken().getToken());

                // Send the graph request
                sendGraphRequest(loginResult.getAccessToken());
            }

            @Override
            public void onCancel(){
                // App code
                // If the login attempt cancelled
                mTextView.setText("Login attempt canceled.");
            }

            @Override
            public void onError(FacebookException exception){
                // App code
                // If the login attempt get an error
                mTextView.setText("Login attempt failed.");
            }
        });
    }

    // Custom method for facebook graph request
    protected void sendGraphRequest(AccessToken accessToken){
        GraphRequest request = GraphRequest.newMeRequest(accessToken,
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {
                        // App code
                        try {
                            // User ID
                            mTVInfo.setText("ID: " + object.getString("id"));

                            // User fill name
                            mTVInfo.setText(mTVInfo.getText() + "\nName : " + object.getString("name"));

                            // User first name and last name
                            mTVInfo.setText(mTVInfo.getText() + "\nFirst name : " + object.getString("first_name"));
                            mTVInfo.setText(mTVInfo.getText() + "\nLast name : " + object.getString("last_name"));

                            // User email
                            mTVInfo.setText(mTVInfo.getText() + "\nEmail : " + object.getString("email"));

                            // User gender
                            mTVInfo.setText(mTVInfo.getText() + "\nGender : " + object.getString("gender"));

                            // User profile link
                            mTVInfo.setText(mTVInfo.getText() + "\nLink : " + object.getString("link"));

                            // User time zone
                            mTVInfo.setText(mTVInfo.getText() + "\nTime zone : " + object.getString("timezone"));

                            // User locale
                            mTVInfo.setText(mTVInfo.getText() + "\nLocale : " + object.getString("locale"));

                            // User updated time
                            mTVInfo.setText(mTVInfo.getText() + "\nUpdated time : " + object.getString("updated_time"));

                            // User verified status
                            mTVInfo.setText(mTVInfo.getText() + "\nVerified : " + object.getString("verified"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

        Bundle parameters = new Bundle();
        parameters.putString(
                "fields",
                "id,name,link,email,gender,last_name,first_name,locale,timezone,updated_time,verified"
        );
        request.setParameters(parameters);
        request.executeAsync();
    }

    // For facebook sdk
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        mCallbackManager.onActivityResult(requestCode, resultCode, data);
    }

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

        // Logs 'install' and 'app activate' App Events.
        AppEventsLogger.activateApp(this);
    }

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

        // Logs 'app deactivate' App Event.
        AppEventsLogger.deactivateApp(this);
    }
}