获取好友列表facebook 3.0

时间:2012-12-19 16:50:55

标签: android facebook facebook-graph-api facebook-android-sdk

我正在尝试使用新的SDK(3.0)从facebook获取我的朋友列表。我遇到的问题涉及我需要在Bundle中插入什么类型的参数以及如何使用newMyFriendRequest和GraphAPI。

我没有在facebook文档中找到关于我们必须使用哪种字段的地方。基于GraphExplorer我在我的Bundle中插入了带有“id,name,friend”字符串的键“fields”作为值。下面的代码显示了我现在正在做的事情。在我得到我的照片和名字后,我执行newMyFriendRequest。我相信它默认使用GraphAPI。

我在StackOverflow上看到过一些相关帖子:

How to send a FQL query with the new Android SDK

Facebook Android SDK request parameters: where find documentation?

它帮助我很少,我不想使用FQL。对于响应II我收到这个JSON就像一个答案:

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

请注意,我是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();
    }
}

7 个答案:

答案 0 :(得分:22)

在getFriends()方法中,更改以下行:

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

通过

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

答案 1 :(得分:11)

使用FQL查询

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); 

参考Run FQL Queries

答案 2 :(得分:8)

这应该有效:

// @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();
        }
    }
});

答案 3 :(得分:6)

不幸的是Facebook删除了这些权限。

/ me / friends会返回正在使用您应用的用户的朋友。

在v2.0中,朋友API端点返回同时使用您的应用的朋友的列表。在v1.0中,回复包括所有人的朋友。

在v1.0中,可以要求允许应用查看有限数量的朋友数据的权限,例如某人的朋友喜欢,他们的生日等等。

在v2.0中,这些权限都已被删除。应用程序不再可能看到来自某个人的朋友的数据,除非这些朋友也已登录到应用程序并授予该应用程序查看该数据的权限

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

答案 4 :(得分:4)

您可以使用我的代码,您需要在项目中使用facebook库。用于facebook的所有类都在那个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和id是两个String数组,现在拥有所有朋友的名字和ID。我希望它能解决你的问题。

答案 5 :(得分:0)

如果该人询问如何获取名字和姓氏,则需要输入first_name和last_name而不是名称。

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

答案 6 :(得分:0)

  

使用以下代码从Facebook获取好友列表。它会   仅显示已完成Facebook登录的用户的数据   使用该应用程序,用户在数据库中拥有Facebook ID。然后   这将显示这些朋友的名单。

<强> 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);
        }
    }



}