Calling Facebook GraphRequest from another class returns null

Markus :

I'm making application that requires to get data from Facebook. To avoid duplicating code I decided to create a class for GraphRequest.

public class FacebookRequest {
private static JSONObject object;

private FacebookRequest(JSONObject object) {
    this.object = object;
}

private static JSONObject GraphApiRequest(String path, AccessToken token){
        new GraphRequest(
                token,
                path,
                null,
                HttpMethod.GET,
                new GraphRequest.Callback() {
                    public void onCompleted(GraphResponse response) {
                        object = response.getJSONObject();
                    }
                }
        ).executeAsync();
    return object;
}

public static JSONObject getGraphApi(String path, AccessToken token){
    return GraphApiRequest(path, token);
}}

To call the class I use

private static FacebookRequest fbRequest;
//....
JSONObject object= fbRequest.getGraphApi(path,token);

The problem is GraphApiRequest method always returns object=null and only after that executes request.

What should I change to get actual object on call?

EDIT: Thanks to This answer

So I found a solution to get object on call, but it's not perfect option (maybe even wrong, since I am not very experienced in programming, but it works for me)

public class FacebookRequest {
    private JSONObject object;

    public FacebookRequest(String path, AccessToken token) {
        new GraphRequest(
                token,
                path,
                null,
                HttpMethod.GET,
                new GraphRequest.Callback() {
                    public void onCompleted(GraphResponse response) {
                        object = response.getJSONObject();
                    }
                }
        ).executeAsync();
    }
    public JSONObject getObject(){
        return object;
    }
}

When I am calling request It get's executed after some time

protected void onCreate(Bundle savedInstanceState) {
    //...
    FacebookRequest fbRequest = new FacebookRequest(path,token);
    //...
}

To get actual object on call I use.

JSONObject object = fbRequest.getObject();

It is still not working if I call for a JSONObject right after creating constructor. I am looking forward to improve this code, If you will give me some advice.

Matteo Gaggiano :

What you are looking for is explained here (Facebook API how to wait til graphRequest executeAsync is done). As you ask, for use it right after creating constructor replace .executeAsyc() with .executeAndWait().

This is not adviced due a freeze on main thread and a bad user experience.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=439890&siteId=1