27

I'm trying to obtain my friend list from facebook using new SDK(3.0). I'm facing problems related to what kind of params I need to insert in a Bundle and how to use newMyFriendRequest and GraphAPI.

I didn't find on facebook documentation a place about what kind of field does we have to use. Based on GraphExplorer I insert in my Bundle the key "fields" with this string "id,name,friend" as a value. The code below shows what I'm doing right now. After I get My picture and name I execute newMyFriendRequest. I believe it uses GraphAPI by default.

I've seen here on StackOverflow some posts related:

How to send a FQL query with the new Android SDK

Facebook Android SDK request parameters: where find documentation?

It helps me little and I don't want to use FQL. For response II'm receiving this JSON like an answer:

{Response:  responseCode: 500, graphObject: null, error: {HttpStatus: 500, errorCode: 100, errorType: FacebookApiException, errorMessage: Unsupported operation}, isFromCache:false}

Notice I'm very new in Facebook SDK for Android.

private void onSessionStateChange(final Session session, SessionState sessionState, Exception ex){
    if(session != null && session.isOpened()){
        getUserData(session);
    }
}

private void getUserData(final Session session){
    Request request = Request.newMeRequest(session, 
        new Request.GraphUserCallback() {
        @Override
        public void onCompleted(GraphUser user, Response response) {
            if(user != null && session == Session.getActiveSession()){
                pictureView.setProfileId(user.getId());
                userName.setText(user.getName());
                getFriends();

            }
            if(response.getError() !=null){

            }
        }
    });
    request.executeAsync();
}

private void getFriends(){
    Session activeSession = Session.getActiveSession();
    if(activeSession.getState().isOpened()){
        Request friendRequest = Request.newMyFriendsRequest(activeSession, 
            new GraphUserListCallback(){
                @Override
                public void onCompleted(List<GraphUser> users,
                        Response response) {
                    Log.i("INFO", response.toString());

                }
        });
        Bundle params = new Bundle();
        params.putString("fields", "id,name,friends");
        friendRequest.setParameters(params);
        friendRequest.executeAsync();
    }
}
Community
  • 1
  • 1
learner
  • 1,311
  • 3
  • 18
  • 39
  • 2
    Have you tried not setting any params? The id and name are there by default, so you don't have to request them. I don't think "friends" is a valid field. Try removing the Bundle and the setParameters altogether, and just call friendRequest.executeAsync(). – Ming Li Dec 19 '12 at 16:56
  • @MingLi Works fine with your observations. My intention is to get friendlist and profile image for each of them. For this, I believe I need to pass a parameter into a bundle. If this is true what param do I need to pass? See, facebook like I said is poor with this type of documentation. – learner Dec 19 '12 at 17:45
  • 2
    then what you want is "id,name,picture" for the "fields" parameter. You can also go to https://developers.facebook.com/tools/explorer/ to try out queries very quickly (in this case I used /me/friends?fields=id,name,picture). – Ming Li Dec 19 '12 at 19:27
  • @MingLi Ok, works very good. – learner Dec 20 '12 at 13:39
  • Sounds you had solved your problem, may I ask how you modify your code to get it work ? – RRTW May 09 '13 at 02:55

7 Answers7

22

In getFriends() method, change this line:

params.putString("fields", "id,name,friends");

by

params.putString("fields", "id, name, picture");
ignacio_gs
  • 378
  • 1
  • 7
11

Using FQL Query

String fqlQuery = "SELECT uid,name,pic_square FROM user WHERE uid IN " +
        "(SELECT uid2 FROM friend WHERE uid1 = me())";

Bundle params = new Bundle();
params.putString("q", fqlQuery);
Session session = Session.getActiveSession();

Request request = new Request(session,
        "/fql",                         
        params,                         
        HttpMethod.GET,                 
        new Request.Callback(){       
    public void onCompleted(Response response) {
        Log.i(TAG, "Result: " + response.toString());

        try{
            GraphObject graphObject = response.getGraphObject();
            JSONObject jsonObject = graphObject.getInnerJSONObject();
            Log.d("data", jsonObject.toString(0));

            JSONArray array = jsonObject.getJSONArray("data");
            for(int i=0;i<array.length();i++){

                JSONObject friend = array.getJSONObject(i);

                Log.d("uid",friend.getString("uid"));
                Log.d("name", friend.getString("name"));
                Log.d("pic_square",friend.getString("pic_square"));             
            }
        }catch(JSONException e){
            e.printStackTrace();
        }
    }                  
}); 
Request.executeBatchAsync(request); 

Ref : Run FQL Queries

Kirit Vaghela
  • 12,572
  • 4
  • 76
  • 80
8

This should work:

// @Deprecated
// Request.executeMyFriendsRequestAsync()

// Use this instead:
Request.newMyFriendsRequest(session, new GraphUserListCallback() {

    @Override
    public void onCompleted(List<GraphUser> users, Response response) 
    {
        if(response.getError() == null)
        {
            for (int i = 0; i < users.size(); i++) {
                Log.e("users", "users " + users.get(i).getName());
            }
        }
        else
        {
            Toast.makeText(MainActivity.this, 
                           response.getError().getErrorMessage(), 
                           Toast.LENGTH_SHORT).show();
        }
    }
});
Antarr Byrd
  • 24,863
  • 33
  • 100
  • 188
Mohit Verma
  • 3,025
  • 1
  • 20
  • 36
  • @proGamer The replacement is to use `Request.newMyFriendsRequest(Session, GraphUserListCallback)`, which returns a `Request` on which you can either call `executeAsync()` or `executeAndWait()` – karl Mar 04 '14 at 23:11
  • @karl How will get the result of `executeAsync() or executeAndWait()` I mean which call back method is called as a result ? – Prateek Mar 11 '14 at 12:25
  • @prateek Just like above - the `GraphUserListCallback` is the same as in Mohit Verma's answer. It receives the `onCompleted` call when the request completes, either with success or failure. – karl Mar 11 '14 at 21:45
  • @Mohit Verma i m working on facebook with new facebook sdk but i dont get the friends list of mine. any idea about it? – Gorgeous_DroidVirus Aug 15 '14 at 07:29
  • This method has been deprecated and it only returns the friends that are using the App from where you are calling the API. – Oscar Salguero Mar 11 '15 at 19:25
6

Unfortunately Facebook remove those permissions.

/me/friends returns the user's friends who are also using your app.

In v2.0, the friends API endpoint returns the list of a person's friends who are also using your app. In v1.0, the response included all of a person's friends.

In v1.0, it was possible to ask for permissions that would allow an app to see a limited amount of friend data, such as a person's friend's likes, their birthdays, and so on.

In v2.0, those permissions have all been removed. It's no longer possible for an app to see data from a person's friends unless those friends have also logged into the app and granted permission for the app to see it that data

https://developers.facebook.com/docs/apps/upgrading#v2_0_friendlist_title

Dennis Mathew
  • 408
  • 5
  • 14
4

You can use my code, you need to use the facebook library in your project. All the classes used for facebook are there in that sdk.

private void onSessionStateChange(Session session, SessionState state,
        Exception exception) {
    if (state.isOpened()) {
        Log.i(TAG, "Logged in...");
        Request.executeMyFriendsRequestAsync(session,
                new GraphUserListCallback() {

                    @Override
                    public void onCompleted(List<GraphUser> users,
                            Response response) {
                        Log.i("Response JSON", response.toString());
                        names = new String[users.size()];
                        id = new String[users.size()];
                        for (int i=0; i<users.size();i++){
                            names[i] = users.get(i).getName();
                            id[i]= users.get(i).getId();                                
                        }                           
                    }
                });
    } else if (state.isClosed()) {
        Log.i(TAG, "Logged out...");
    }
}

names and ids are two String arrays and now have all the names and ids of the friends. I hope it solves your problem.

Anas Azeem
  • 2,820
  • 3
  • 24
  • 37
  • Not working. It was deprecated and now it only returns the friends that are using the App from where you are calling the API. – Oscar Salguero Mar 11 '15 at 19:26
0

For the person ask how obtein the first name and the last name, you need put first_name and last_name instead of name.

params.putString("fields", "id, first_name, last_name, picture");
0

Use the following code to get the friend list from Facebook. It will show only the data of those users who has been done Facebook login with the app, and the users have Facebook id's on the database. then this will show the list of those friends.

FacebookFriendListActivity.java

package com.application.Activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestBatch;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionDefaultAudience;
import com.facebook.SessionLoginBehavior;
import com.facebook.SessionState;
import com.facebook.internal.SessionTracker;
import com.facebook.internal.Utility;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphUser;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import Info.InfoUsers;
import india.application.upflair.Adapter.FindPeopleAdapter;
import india.application.upflair.R;
import utills.ConnectionDetector;
import utills.Constant;

public class FacebookFriendListActivity extends AppCompatActivity {



    //facebook section
    SessionTracker mSessionTracker;
    Session mCurrentSession = null;

    String facebook_id;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview);


        signInWithFacebook();


    }

    /***
     * facebook section to get friend list
     */
    private void signInWithFacebook() {
        mSessionTracker = new SessionTracker(getBaseContext(), new Session.StatusCallback() {
            @Override
            public void call(Session session, SessionState state, Exception exception) {
                //TODO..
            }
        },
                null, false);

        String applicationId = Utility.getMetadataApplicationId(getBaseContext());
        mCurrentSession = mSessionTracker.getSession();
        mSessionTracker.setSession(null);
        Session session = new Session.Builder(getBaseContext()).setApplicationId(applicationId).build();
        Session.setActiveSession(session);
        mCurrentSession = session;

        if (!mCurrentSession.isOpened()) {
            Session.OpenRequest openRequest = null;
            openRequest = new Session.OpenRequest(FacebookFriendListActivity.this);
            if (openRequest != null) {
                openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS);
                openRequest.setPermissions(Arrays.asList("user_birthday", "email", "user_location", "user_friends"));
                openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
                mCurrentSession.openForRead(openRequest);
                accessFacebookUserInfo();


            }
        } else {
            accessFacebookUserInfo();
        }
    }

    Request friendListRequest = null;
    private void accessFacebookUserInfo() {
        if (Session.getActiveSession() != null & Session.getActiveSession().isOpened()) {



            Request cover_request = new Request(Session.getActiveSession(), "me", null, HttpMethod.GET, new Request.Callback() {
                @Override
                public void onCompleted(Response response) {}
            });
            Request.executeBatchAsync(cover_request);

            Request meRequest = Request.newMeRequest(Session.getActiveSession(),new Request.GraphUserCallback() {
                @Override
                public void onCompleted(GraphUser user, Response response) {
                    try {

                        friendListRequest.executeAsync();

                    } catch (Exception jex) {
                        jex.printStackTrace();
                    }
                }
            });

            RequestBatch requestBatch = new RequestBatch(meRequest);

            requestBatch.addCallback(new RequestBatch.Callback() {
                @Override
                public void onBatchCompleted(RequestBatch batch) {}
            });
            requestBatch.executeAsync();

            friendListRequest = new Request(Session.getActiveSession(), "/me/friends", null, HttpMethod.GET, new Request.Callback() {
                @Override
                public void onCompleted(Response response) {
                    try {
                        GraphObject graphObj = response.getGraphObject();
                        if (graphObj != null) {

                            JSONObject jsonObj = graphObj.getInnerJSONObject();
                            JSONArray data=jsonObj.getJSONArray("data");

                            if(data.length()>0 && data!=null)
                            {
                                for(int i=0;i<data.length();i++)
                                {
                                    JSONObject dataobj= data.getJSONObject(i);

                                    String name=dataobj.getString("name");
                                    String id=dataobj.getString("id");

                                    System.out.println("name==============" + name);
                                    System.out.println("id==============" + id);

                                    facebooklist.add(id);

                                    facebook_id = facebooklist.toString().replace("[", "");
                                    facebook_id = facebook_id.replace("]", "");

                                }




                            }


                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
            if (mCurrentSession.isOpened()) {

                accessFacebookUserInfo();
            }
            else {
                Toast.makeText(mContext, "some thing went wrong plz try later", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(mContext, "some thing went wrong plz try later", Toast.LENGTH_LONG).show();
            mCurrentSession = null;
            mSessionTracker.setSession(null);
        }
    }



}
gAuRaV jAiN
  • 544
  • 5
  • 9