Get friend list facebook 3.0

帅比萌擦擦* 提交于 2019-12-29 02:47:05

问题


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

回答1:


In getFriends() method, change this line:

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

by

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



回答2:


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




回答3:


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



回答4:


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




回答5:


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.




回答6:


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



回答7:


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



}


来源:https://stackoverflow.com/questions/13957181/get-friend-list-facebook-3-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!