Android Get Information of Facebook Pages Liked by User Tutorial

Udemy Generic 728x90

Objective

In this tutorial, we will learn how to get the Information of Facebook Page liked by the user in an Android Application through a simple example.

 


 

Facebook SDK provides a various APIs to fetch information related to Facebook user and use that information in another Android application. We already covered the topics where developers can use the Facebook SDK to integrate Facebook Login, get User Email, User information such as name, number, etc and share content from Android app to Facebook.

In this tutorial, we will learn the process to fetch information related to various Facebook pages liked by the user.
 

Step 2

Create New Project & Integrate Facebook SDK

First step in fetching the page information is integrating Facebook SDK in Android App and authenticate your app using Facebook login. So, first create a new application in Android Studio, name FacebookLiked Page. Next, you need to integrate Facebook and to do so, follow Android Facebook Integration And Login Tutorial.

Once your Facebook Integration is done, you will have an app with Facebook Login functionality and permission to fetch user information, i.e, name and email.

 

Step 3

Add Permission for Facebook Page Information

Facebook provides access to only that information for which your app has the permission. So, to access Liked page information you need to request for the necessary permissions. Permission to access information of pages liked by user is “user_likes“. So, to add the permission, open MainActivity.java file and traverse to setReadPermissions() method. This method already has a permission, named email to access user email. Add “user_likes” permission there too.
Your code snippet now will look like this :

loginButton.setReadPermissions("email,user_likes");

 

Step 4

Fetch Information of Liked Pages

Once you have requested the permission, Facebook will let your app access the desired information. So, before fetching the information you need to authenticate the app through Facebook Login. After authentication, Facebook will send authentication token on success callback. Create a method, named getLikedPageInfo() to request and parse the information received from Facebook. Facebook has Graph APIs defined specifically to request the data using received authentication token.

Within the scope of getLikedPageInfo() method, implement GraphRequest.newMeRequest() method that will take token as argument. Once the graph request callback is complete, it will provide a JSONObject and GraphResponse as result. JSONObject has the information we requested for.
Here is the sample code to implement GraphRequest and retrieve the information :

  /*
   * To get the Facebook page which is liked by user's through creating a new request.
   * When the request is completed, a callback is called to handle the success condition.
   */
  protected void getLikedPageInfo(LoginResult login_result){

        GraphRequest data_request = GraphRequest.newMeRequest(
                login_result.getAccessToken(),
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(
                            JSONObject json_object,
                            GraphResponse response) {

                       try {
                           // convert Json object into Json array
                           JSONArray posts = json_object.getJSONObject("likes").
optJSONArray("data");

                           for (int i = 0; i < posts.length(); i++) {

                               JSONObject post = posts.optJSONObject(i);
                               String id = post.optString("id");
                               String category = post.optString("category");
                               String name = post.optString("name");
                               int count = post.optInt("likes");
                               // print id, page name and number of like of facebook page
                               Log.e("id -", id+"
                                     name -"+name+ " category-"+
                                     category+ " likes count -" + count);
                           }

                       } catch(Exception e){

                       }
                    }
                });
        Bundle permission_param = new Bundle();
        // add the field to get the details of liked pages
        permission_param.putString("fields", "likes{id,category,name,location,likes}");
        data_request.setParameters(permission_param);
        data_request.executeAsync();
    }

 

Step 5

Run Application

So, app to get information of Facebook Pages liked by the user is now complete. To test it, run the application. Once the app is in running status, it will show a screen with Facebook login. Log to the app using fb login button and after authentication you will be able to see pages liked by the user in Android Studio’s Log.

like_details

 

Step 6

Final Code

Here is the complete code for main activity class :

public class MainActivity extends AppCompatActivity {
    CallbackManager callbackManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //initialize the facebook SDK
        facebookSDKInitialize();
        setContentView(R.layout.activity_main);
        // initialize the id of login button
        LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
        // set the facebook permission
        loginButton.setReadPermissions("email,user_likes");
        // call the getLoginDetails() method to login with facebook
        getLoginDetails(loginButton);
 }

 /**
  * Initialize the facebook sdk and then callback manager will handle the login responses.
  */
   protected void facebookSDKInitialize() {

        FacebookSdk.sdkInitialize(getApplicationContext());

        callbackManager = CallbackManager.Factory.create();
    }

   /*
    * Register a callback function with LoginButton to respond to the login result.
    * On successful login,login result has new access token and  recently granted permissions.
    */

    protected void getLoginDetails(LoginButton login_button){

        // Callback registration
        login_button.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult login_result) {

                getLikedPageInfo(login_result);
            }

            @Override
            public void onCancel() {
                // code for cancellation
            }

            @Override
            public void onError(FacebookException exception) {
                //  code to handle error
            }
        });
    }
  /*
   * To get the Facebook page which is liked by user's through creating a new request.
   * When the request is completed, a callback is called to handle the success condition.
   */
    protected void getLikedPageInfo(LoginResult login_result){

        GraphRequest data_request = GraphRequest.newMeRequest(
                login_result.getAccessToken(),
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(
                            JSONObject json_object,
                            GraphResponse response) {

                       try {

                           JSONArray posts = json_object.getJSONObject("likes").optJSONArray("data");
                           Log.e("data1",posts.toString());
                           for (int i = 0; i < posts.length(); i++) {

                               JSONObject post = posts.optJSONObject(i);
                               String id = post.optString("id");
                               String category = post.optString("category");
                               String name = post.optString("name");
                               int count = post.optInt("likes");
                               // print id, page name and number of like of facebook page
                               Log.e("id -", id+"
                                     name -"+name+ " category-"+
                                     category+ " likes count -" + count);
                           }

                       } catch(Exception e){

                       }

                    }
                });
        Bundle permission_param = new Bundle();
        permission_param.putString("fields", "likes{id,category,name,location,likes}");
        data_request.setParameters(permission_param);
        data_request.executeAsync();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.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);
    }
}

 

Udemy Generic 728x90

Spread the word. Share this post!

  • sushant

    how can display a yahoo finance stock graph … mail me [email protected]… thx..

  • Raja Mohamed

    i did not get output,but the code does not show error.then what is the problem

  • Ehsan Ullah

    Great help thanks :)

  • TARUN UMATH

    This can work fine thanks for code

  • Dilipkumar Pandit

    the download link is not working please fix it