Facebook login and retrieve profile data in Android

Add Facebook dependency in your app level gradle file.

compile 'com.facebook.android:facebook-android-sdk:[4,5)'

Always check https://developers.facebook.com/ for the latest version of their Android SDK.

Now add following things in your manifest file.

Add this meta-data and activity declaration inside your application tag.

<meta-data
  android:name="com.facebook.sdk.ApplicationId"
  android:value="@string/facebook_app_id" />
<activity
  android:name="com.facebook.FacebookActivity"
  android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
  android:label="@string/app_name" />
<activity
  android:name="com.facebook.CustomTabActivity"
  android:exported="true">
    <intent-filter>
      <action android:name="android.intent.action.VIEW" />
      <category android:name="android.intent.category.DEFAULT" />
      <category android:name="android.intent.category.BROWSABLE" />
      <data android:scheme="@string/fb_login_protocol_scheme" />
    </intent-filter>
</activity>

Please add 2 strings ‘facebook_app_id’ and ‘fb_login_protocol_scheme’ from your Facebook app. You will already have ‘app_name’ string created in your project by Android Studio.

Now add this 2 line in your Application class(the class extending Application).

FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);

Now we add one button in our layout which will do login/logout functionality.

<Button
  android:id="@+id/btn"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Login" />

Here is the coding for the java file, i.e. MainActivity.java

public class MainActivity extends AppCompatActivity {
  private Button btn;
  private CallbackManager callbackManager;
  private AccessTokenTracker accessTokenTracker;
  private AccessToken accessToken;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FacebookSdk.sdkInitialize(this.getApplicationContext());

    btn = (Button) findViewById(R.id.btn);

    callbackManager = CallbackManager.Factory.create();

    accessTokenTracker = new AccessTokenTracker() {
      @Override
      protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
        accessToken = currentAccessToken;
        if (accessToken == null) {
          btn.setText("LOGIN");
        }
        else {
          btn.setText("LOGOUT");
          GraphRequest request = GraphRequest.newMeRequest(accessToken,
            new GraphRequest.GraphJSONObjectCallback() {
              @Override
              public void onCompleted(JSONObject object, GraphResponse response  {
                if (null != object) {
                  //your json object here, access user data here
                  Log.e("test", "json: " + object.toString());
                }
                else {
                  Log.e("test", "json: null");
                }
              }
            });
            Bundle parameters = new Bundle();
            parameters.putString("fields",  "id,birthday,first_name,gender,last_name,location,name,locale,timezone,updated_time,verified,email,hometown");
            request.setParameters(parameters);
            request.setAccessToken(accessToken);
            request.executeAsync();
          }
        }
      };

      accessToken = AccessToken.getCurrentAccessToken();
      if (null != accessToken) {
        btn.setText("LOGOUT");
      } else {
        btn.setText("LOGIN");
      }

      btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          if ("LOGOUT".equals(btn.getText().toString())) {
            LoginManager.getInstance().logOut();
          } else {
          LoginManager.getInstance().logInWithReadPermissions(MainActivity1.this, Arrays.asList("public_profile", "email", "user_birthday", "user_hometown", "user_location"));
          }
        }
      });
  }

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

  @Override
  public void onDestroy() {
    super.onDestroy();
    accessTokenTracker.stopTracking();
  }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s