简体   繁体   中英

Android: get facebook friends list

I am using the Facebook SDK to post messages on walls.

Now I need to fetch the Facebook friends list. Can anybody help me with this?

-- Edit --

try {

  Facebook mFacebook = new Facebook(Constants.FB_APP_ID);
  AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
  Bundle bundle = new Bundle();
  bundle.putString("fields", "birthday");
  mFacebook.request("me/friends", bundle);

} catch(Exception e){
    Log.e(Constants.LOGTAG, " " + CLASSTAG + " Exception = "+e.getMessage());
}

When I execute my activity , I'm not seeing anything, but in LogCat there is a debug message like:

06-04 17:43:13.863: DEBUG/Facebook-Util(409): GET URL: https://graph.facebook.com/me/friends?format=json&fields=birthday

And when I tried to access this url directly from the browser, I'm getting the following error response:

{
  error: {
  type: "OAuthException"
  message: "An active access token must be used to query information about the current user."
 }
}

You are about half way there. You've sent the request, but you haven't defined anything to receive the response with your results. You can extend BaseRequestListener class and implement its onComplete method to do that. Something like this:

public class FriendListRequestListener extends BaseRequestListener {

    public void onComplete(final String response) {
        _error = null;

        try {
            JSONObject json = Util.parseJson(response);
            final JSONArray friends = json.getJSONArray("data");

            FacebookActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    // Do stuff here with your friends array, 
                    // which is an array of JSONObjects.
                }
            });

        } catch (JSONException e) {
            _error = "JSON Error in response";
        } catch (FacebookError e) {
            _error = "Facebook Error: " + e.getMessage();
        }

        if (_error != null)
        {
            FacebookActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(getApplicationContext(), "Error occurred:  " + 
                                    _error, Toast.LENGTH_LONG).show();
                }
            });
        }
    }
}

Then in your request you can specify the request listener to use for receiving the response from the request, like this:

mFacebook.request("me/friends", bundle, new FriendListRequestListener());

Using FQL Query

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

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

I was dealing with that and I found the answer. The problem is that you want to access to your data without previous registration with your facebook token.

First, you must to define your Facebook variable:

Facebook mFacebook = new Facebook(getString(R.string.fb_id));

Later, define your AsyncFacebookRunner:

final AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);

Ok, now you must to authorize your request, with autorize method. Note that you must implement callback methods on DialogListener(), put attention on onComplete() method. On that method you must to run the friend fetch request. Now your request will pass because now you are authenticated. Now the code:

mFacebook.authorize(this, fb_perms, new DialogListener(){
        /**
         * Triggered on a successful Facebook registration. 
         */
        public void onComplete(Bundle values) {
            mAsyncRunner.request("me/friends", new FriendListRequestListener());
        }

        /**
         * Triggered on a FacebookError.
         */
        public void onFacebookError(FacebookError e) {

        }

        /**
         * Triggered on a DialogError.
         */
        public void onError(DialogError e) {

        }

        /**
         * Triggered when the User cancels the Facebook Login.
         */
        public void onCancel() {

        }
    });

You can use the FriendListRequestListener class that was post by @Kon

I hope this helps.

Cheers!

I faced the same problem yesterday. I wondering if you have overriden the onActivityResult() function?

private Facebook mFacebook=null;

...
...
...

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

I'm doing something like this is working good....

                    jsonObj = Util.parseJson(facebook.request("me/friends"));

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

                            JSONObject json_data = jArray.getJSONObject(i);
                            Log.v("THIS IS DATA", i+" : "+jArray.getJSONObject(i));
                     }

Hope it is helpful...

Check this answer in order to know how to get Facebook friend list and who of these friends have installed your app using new Facebook SDK 3.0 for Android.

If somebody is reading this in late 2015, the answer and code is quite simple. Take a look at official documentationhere (in the code window click on Android SDK). Keep in mind that you need to have user_friends permission.

Bro tip for android-rx users - get your friends synchronously, then process message and return Observable:

public Observable<List<Friend>> execute() {
    return Observable.defer(new Func0<Observable<List<Friend>>>() {
        @Override
        public Observable<List<Friend>> call() {
            AccessToken a = AccessToken.getCurrentAccessToken();
            if (Utils.isValid(a)) {
                try {
                    GraphResponse res = new GraphRequest(AccessToken.getCurrentAccessToken(), "me/friends").executeAndWait();

                    // process result          

                    return Observable.just(your friend list);
                } catch (Exception e) {
                   // notify user or load again
                }
            }
            // invalid access token -> notify user
        }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM