我有程序使用Facebook Graph API从Facebook图像获取各种帖子的帖子ID。这是我用过的代码:
的OnCreate()
public class MainActivity extends AppCompatActivity {
//Variable Declarations
TextView textView1;
public ArrayList<String> postIds = new ArrayList<>();//array to store various post ids
ArrayList<String> imageIds = new ArrayList<>();//has the various imageURLs
ImageView img1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getPosts();
System.out.println("PostIDS value in Main Activity:"+postIds.toString());
System.out.println("Done Execution From Main Activity");
}//onCreate
Getposts():
public void getPosts()
{
GraphRequest request = GraphRequest.newGraphPathRequest(
a,
"/internationalchaluunion",
new GraphRequest.Callback() {
@Override
public void onCompleted(GraphResponse response) {
// Insert your code here
System.out.println("Response::" + String.valueOf(response.getJSONObject()));
JSONObject jsRoot = response.getJSONObject();
JSONObject jsArr1 = null;
try {
jsArr1 = jsRoot.getJSONObject("posts");
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray arr1 = jsArr1.optJSONArray("data");
//iterate JSONArray and store the values to different
for(int i=0; i < arr1.length(); i++)
{
try {
JSONObject jsonObject = arr1.getJSONObject(i);
//System.out.println("Id"+i+":"+jsonObject.optString("id"));
String str = jsonObject.optString("id");
str=str.substring(str.indexOf("_")+1,str.length());
postIds.add(str);
}//try
catch (JSONException e) {
e.printStackTrace();
}//catch
}//for
/
}//onCompletedMethod
});
Bundle parameters = new Bundle();
parameters.putString("fields", "posts");
request.setParameters(parameters);
request.executeAsync();
}
当我尝试在getposts()函数中访问postID的值时,我可以看到所有值都设置正确。但是当我尝试从main方法或任何其他方法访问postsIds []时是同一个类postIDs []是一个空数组。你能告诉我这里缺少什么。
答案 0 :(得分:0)
查看您的代码,我们可以确认您正在执行异步调用,以便在 getPosts();
中获取所需数据最好尽可能在 onComplete() 回调中使用获取的数据,因为您永远不知道异步任务将执行多长时间 - 因为它取决于在网络/处理器/重计算(如果内部存在)。
在Android中检查此ui-router通用AsyncTask