我正在製作需要從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 。我期待着改進這個代碼,如果你會給我一些建議。
您必須等待響應(您不等待'.executeAsyc()'),然後如果想在創建構造函數*後立即獲取對象*,請使用getObject()。 可以通過'FacebookRequest'constructor中的'.executeAndWait()'替換'.executeAsync()'來完成 –