我正在使用Facebook图形请求来检索朋友列表。但是,如何在调用graphRequest.executeAsync()完成后创建函数并返回它?

private Map<String, String> getFacebookFriends(AccessToken accessToken, Profile profile) throws InterruptedException, ExecutionException {
    final Map<String, String> friendsMap = new HashMap<>();
    GraphRequest graphRequest = new GraphRequest(accessToken, "/me/friends", null, HttpMethod.GET,
            new GraphRequest.Callback() {
                public void onCompleted(GraphResponse response) {
                    JSONObject jGraphObj = response.getJSONObject();
                    try {
                        JSONArray friendsData = jGraphObj.getJSONArray("data");
                        for (int i = 0; i < friendsData.length(); i++) {
                            JSONObject friend = friendsData.getJSONObject(i);
                            String friendId = friend.getString("id");
                            String friendName = friend.getString("name");
                            friendsMap.put(friendId, friendName);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
    );
    List<GraphResponse> gResponseList = graphRequest.executeAsync().get();
    return friendsMap;
}


我目前正在使用与this post中相同的技术。通过像graphRequest.executeAsync().get();这样调用。但似乎不起作用。

上面的函数将在完成friendsMap之前返回graphRequest

任何建议表示赞赏。

最佳答案

我已经通过使用executeAndWait而不是executeAsync函数来工作了。所以,这就是决赛的样子

public static Map<String, String> getFacebookFriends(AccessToken accessToken, Profile profile) throws InterruptedException, ExecutionException {
    final Map<String, String> friendsMap = new HashMap<>();

    GraphRequest.Callback gCallback = new GraphRequest.Callback() {
        public void onCompleted(GraphResponse response) {
            JSONObject jGraphObj = response.getJSONObject();
            try {
                JSONArray friendsData = jGraphObj.getJSONArray("data");
                for (int i = 0; i < friendsData.length(); i++) {
                    JSONObject friend = friendsData.getJSONObject(i);
                    String friendId = friend.getString("id");
                    String friendName = friend.getString("name");
                    friendsMap.put(friendId, friendName);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    final GraphRequest graphRequest = new GraphRequest(accessToken, "/me/friends", null, HttpMethod.GET, gCallback);
    // Run facebook graphRequest.
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            GraphResponse gResponse = graphRequest.executeAndWait();
        }
    });
    t.start();
    t.join();
    return friendsMap;
}

07-27 13:39