从另一个类调用Facebook GraphRequest返回null

Mar*_*kus 10 java android facebook

我正在制作需要从Facebook获取数据的应用程序.为了避免重复代码,我决定为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);
}}
Run Code Online (Sandbox Code Playgroud)

打电话给我使用的课程

private static FacebookRequest fbRequest;
//....
JSONObject object= fbRequest.getGraphApi(path,token);
Run Code Online (Sandbox Code Playgroud)

问题是GraphApiRequest方法始终返回,object=null并且只有在执行请求之后.

我应该改变什么来获得实际的对象?

编辑: 感谢这个答案

所以我找到了一个让对象随叫随到的解决方案,但它不是完美的选择(可能甚至是错的,因为我在编程方面不是很有经验,但它对我有用)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我打电话请求它在一段时间后被执行

protected void onCreate(Bundle savedInstanceState) {
    //...
    FacebookRequest fbRequest = new FacebookRequest(path,token);
    //...
}
Run Code Online (Sandbox Code Playgroud)

为了获得实际的对象,我使用.

JSONObject object = fbRequest.getObject();
Run Code Online (Sandbox Code Playgroud)

如果我在创建构造函数后立即调用JSONObject,它仍然无法工作.我期待着改进这段代码,如果你能给我一些建议.

Mat*_*ano 4

这里解释了您要查找的内容(Facebook API 如何等待 graphRequestexecuteAsync 完成)。正如您所要求的,要在创建构造函数后立即使用它,请替换.executeAsyc().executeAndWait().

由于主线程冻结和糟糕的用户体验,不建议这样做。