-2

I'm using the graph api of facebook for android. I can not bring out any value from GraphRequest([...]).executeAsync(). So the return string is always empty

public String getPost(){
        new GraphRequest(
                AccessToken.getCurrentAccessToken(), "me?fields=friends,name", null, HttpMethod.GET,
                new GraphRequest.Callback() {
                    public void onCompleted(GraphResponse response) {

                        JSONObject object = response.getJSONObject();
                        try {
                            friends = object.getJSONObject("friends").getJSONObject("summary").getString("total_count");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        };

                    }
                }
        ).executeAsync();

        return friends;
}
Pramod Tapaniya
  • 1,228
  • 11
  • 30
Afol
  • 11
  • 4
  • Well of course, it's an async call. It's literally called `executeAsync`. `friends` isn't set when you return, it's set in `onCompleted` which will be called some time in the future, specifically when that `GraphRequest` is completed (hence the name `onCompleted`). It's like asking why a response to your letter didn't magically appear in your hand after putting the letter into a mailbox. – Max Vollmer May 23 '18 at 09:36
  • 1
    Possible duplicate of [Wrapping an asynchronous computation into a synchronous (blocking) computation](https://stackoverflow.com/questions/2180419/wrapping-an-asynchronous-computation-into-a-synchronous-blocking-computation) – Max Vollmer May 23 '18 at 09:38

1 Answers1

0

return friends will return the default friends. you are not getting the behavior of executeAsync() here. executeAsync() will run asynchronously and method will return immediately after scheduling the executeAsync() Task.

The data i.e friends is modifying inside the callback method so you have to return it from onCompleted().

To return data you can use a callback interface See How to define callback.

ADM
  • 20,406
  • 11
  • 52
  • 83