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

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

问题描述:

我正在制作需要从Facebook获取数据的应用程序。 为了避免重复代码,我决定为GraphRequest创建一个类。从另一个类中调用Facebook GraphRequest返回null

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

要调用类的我用

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

问题是GraphApiRequest方法总是返回object=null,只执行请求后。

我该如何改变以获得实际的对象?

编辑: 由于This answer

所以我找到了一个解决方案,使呼叫对象,但它并不完美选择(甚至是错误的,因为我不是很编程经验,但它工作我)

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

当我打电话要求它得到的一段时间后,执行

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

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

JSONObject object = fbRequest.getObject(); 

它仍然没有工作,如果我创建构造后立即要求一个JSONObject 。我期待着改进这个代码,如果你会给我一些建议。

+0

您必须等待响应(您不等待'.executeAsyc()'),然后如果想在创建构造函数*后立即获取对象*,请使用getObject()。 可以通过'FacebookRequest'constructor中的'.executeAndWait()'替换'.executeAsync()'来完成 –

你在找什么在这里解释(Facebook API how to wait til graphRequest executeAsync is done)。 正如你问,创建构造函数.executeAsyc()替换.executeAndWait()后使用它

由于主线程冻结和用户体验不佳,因此不提供此建议。

+0

最后,感谢您为我提供此链接。 – Markus

+0

是@Matteo你是对的我也有同样的问题,我解决这个解决方案。 –

你为什么不跟着https://developers.facebook.com/docs/android/graph/本文档和使用这种方法GraphRequest.newMeRequest()

+0

我在我的问题中提到的是“为了避免重复代码,我决定为GraphRequest创建一个类。 我没有任何问题来获取活动中的数据。 我想要实现的是从任何类获取JSONObject,只需调用'JSONObject object = fbRequest.getGraphApi(path,token); '没有提出新的请求功能。 – Markus

而不是调用的。 private static FacebookRequest fbRequest;静态地,你应该在构造函数中调用,这样你的对象不会为空,并且作为存储在对象中的响应的返回,你将接收到的数据而不是null。