簡體   English   中英

Android:獲取facebook好友列表

[英]Android: get facebook friends list

我正在使用Facebook SDK在牆上發布消息。

現在我需要獲取 Facebook 好友列表。 有人可以幫我嗎?

- 編輯 -

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

當我執行我的activity時,我什么也沒看到,但是在LogCat中有一條調試消息,例如:

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

當我嘗試直接從瀏覽器訪問此 url 時,我收到以下錯誤響應:

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

你已經到了一半。 您已發送請求,但尚未定義任何內容以接收帶有結果的響應。 您可以擴展BaseRequestListener class 並實現其onComplete方法來做到這一點。 像這樣的東西:

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

然后在您的請求中,您可以指定用於接收請求響應的請求偵聽器,如下所示:

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

使用 FQL 查詢

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

我正在處理這個問題,我找到了答案。 問題是您想在沒有事先注冊 facebook 令牌的情況下訪問您的數據。

首先,您必須定義您的 Facebook 變量:

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

稍后,定義您的 AsyncFacebookRunner:

final AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);

好的,現在您必須使用 autorize 方法授權您的請求。 請注意,您必須在 DialogListener() 上實現回調方法,注意 onComplete() 方法。 在該方法上,您必須運行朋友獲取請求。 現在您的請求將通過,因為您現在已通過身份驗證。 現在代碼:

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() {

        }
    });

您可以使用@Kon 發布的 FriendListRequestListener class

我希望這有幫助。

干杯!

我昨天遇到了同樣的問題。 我想知道你是否覆蓋了onActivityResult() function?

private Facebook mFacebook=null;

...
...
...

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

我正在做這樣的事情很好....

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

希望對您有所幫助...

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.

如果有人在 2015 年末閱讀這篇文章,答案和代碼非常簡單。 此處查看官方文檔(在代碼 window 中單擊 Android SDK)。 請記住,您需要擁有 user_friends 權限。

android-rx 用戶的兄弟提示 - 同步獲取您的朋友,然后處理消息並返回 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());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM